下面是一个采用拉锯式排序法对数组元素按升序进行排序的程序,所谓“拉锯式排序法”是这一遍把最小的元素从下往上移动到最上面的位置,下一遍则是从上往下把最大的元素移动到最下面的位置。 程序运行效果如下图所示。
Private Sub Command1_Click()
Dim a(10) As Integer, i As Integer
Randomize ′产生不同的随机数
For i = 1 To 10
a(i) = Int(Rnd * 100) + 1
Text1.Text = Text1.Text & Str(a(i))
Next i
Call Shaker_sort(a()) '调用Shaker_sort
For i = 1 To 10
Text2.Text = Text2.Text & Str(a(i))
Next i
End Sub
Private Sub Shaker_sort(k() As Integer)
Dim i As Integer,c As Integer,d As Integer
Dim t As Integer
c = 1
d = 10
Do While c<=d
For i= '从下往上把最小的元素移到最上面的位置
If k(i-1)>k(i) Then
t = k(i - 1):k(i- 1) = k(i):k(i) = t
End If
Next i
For i = c+1 To d-c '从上到下把最大的元素移到最下面的位置
If Then
t = k(i+1):k(i+1) = k(i):k(i) = t
End If
Next i
c = c + 1
Loop
End Sub