排序在電腦科學中是一個重要的部分,在這個問題中將限定使用一種排序方式,就是你只能交換相鄰的2個元素。將數列由小到大排序,並計算出最少要交換幾次才能排好。例如給你1 2 3,那需要交換的次數為0,因為已經排好了。例如給你2 3 1這個數列,第一次交換1跟3變成2 1 3,第二次交換2跟1變成1 2 3,因此最少需要交換2次才可排好。
輸入說明:輸入之奇數列為下一行數列中的個數,偶數列為數列資料,代表一組測試資料。每個數字與數字間的區隔為一個空白符號,當奇數列為0時表示結束。(請參照輸入範例)
輸入範圍:每個數列最少有2個數字,最多不超過100個。每個數列中的數字皆大於0,小於1000,且不重覆。
輸入範例:in.txt
3
1 2 3
3
2 3 1
0
輸出說明:對每一組輸入資料,輸出最少需要交換的次數。(請參照輸出範例)
輸出範例:out.txt
0
2
Private Sub Form_Load()
回覆刪除Dim c As Integer
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Do
c = 0
Input #1, n
If n = 0 Then Exit Do
Line Input #1, x
a = Split(x)
For j = 0 To UBound(a)
For i = 0 To UBound(a) - 1
If a(i) > a(i + 1) Then
b = a(i)
a(i) = a(i + 1)
a(i + 1) = b
c = c + 1
End If
Next
Next
Print #2, c
Loop Until n = 0
Close
Close
End
End Sub
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Do
c = 0
Input #1, n
If n = 0 Then Exit Do
Line Input #1, p
a = Split(p)
For i = 0 To UBound(a)
For j = 0 To UBound(a) - 1
If a(j) > a(j + 1) Then
b = a(j)
a(j) = a(j + 1)
a(j + 1) = b
c = c + 1
End If
Next j
Next i
Print #2, c
Loop
Close #2
Close #1
End
End Sub
作者已經移除這則留言。
回覆刪除Private Sub Form_Load()
回覆刪除Dim a() As Integer
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Do While Not EOF(1)
z = 0
Input #1, n
If Val(n) = 0 Then Exit Do
ReDim a(Val(n))
For i = 1 To Val(n)
Input #1, r
a(i) = Val(r)
Next i
For i = 1 To Val(n) - 1
For j = 2 To Val(n)
If a(j) < a(j - 1) Then
maxn = a(j - 1)
a(j - 1) = a(j)
a(j) = maxn
z = z + 1
End If
Next j
Next i
Print #2, z
Loop
Close #2
Close #1
End
End Sub