关于数组排序问题
题目:假设数组有n个元素,需要对其按递增的顺序进行排序。(采用冒泡法)例题的方法是:
private sub form_load()
Dim a(1 To 10) As Integer
Dim temp As Long
For i = 1 To 10
a(i) = Int(51 * Rnd + 10)
Next i
Print "排序前:"
For i = 1 To 10
Print a(i);
Next i
For i = 10 To 2 step -1
For j = 1 To i-1
If a(j) > a(j + 1) Then
temp= a(j)
a(j) = a(j + 1)
a(j + 1) = temp
End If
Next j
Next i
Print "排序后:"
For i = 1 To 10
Print a(i);
Next i
End Sub
而我觉得用两次嵌插循环太复杂,况且题目也没给j定义类型,所以在我用一次嵌插循环。
Private Sub Form_Load()
Dim a(1 To 10) As Integer
Dim temp As Long
For i = 1 To 10
a(i) = Int(51 * Rnd + 10)
Next i
Print "排序前:"
For i = 1 To 10
Print a(i);
Next i
For i = 1 To 9
If a(i) > a(i + 1) Then
temp = a(i)
a(i) = a(i + 1)
a(i + 1) = temp
End If
Next i
Print "排序后:"
For i = 1 To 10
Print a(i);
Next i
End Sub
可是运行后排列的顺序是错的,不是递增。结果如图:
本人是初学者,望请各位前辈指点。