為此,編寫了一個 VB 程序,功能如下:運行程序,窗體加載時隨機產(chǎn)生 10 個隨機整數(shù),并在列表框 List1 中依次顯示排序前數(shù)據(jù),單擊“排序”按鈕 Command1,在列表框 List2 中 顯示經(jīng)過上述排序算法后的數(shù)據(jù),運行結(jié)果如圖 b 所示。實現(xiàn)上述功能的 VB 代碼如下,但加框處代碼有錯,請改正。 Const n=10 Dim a(1To n) As Integer'生成 n 個隨機數(shù),存儲在 a 數(shù)組,代碼略 Private Sub Command1_Click ( ) Dim i As Integer,j As Integer,t As Integer For i=2To n t=a(i):j=i-1 Do While t<a(j) a(j+1)=a(j) j=j-1 If Then Exit Do Loop
Next i For i=1To n List2.AddItem Str(a(i)) Next i End Sub
是待排序的數(shù)據(jù),數(shù)據(jù)從a(1)開始存放;整數(shù)型參數(shù)n表示傳入的數(shù)組長度,該函數(shù)的返回值也是一個整數(shù)型數(shù)組.所以調(diào)用此函數(shù)實現(xiàn)排序非常方便: 比如有一個整數(shù)型數(shù)組a(1 to 10)需要降序排序,可以直接這樣調(diào)用: a
=bubble_sort(False,a
,10) 該函數(shù)VB代碼如下: Function bubble_sort(sx As Boolean,a
As Integer,n As Integer) As Integer
Dim i,j,t As Integer For i=1 To n-1 For j=
Step-1 If
Then If a(j)<a(j-1)Then t=a(j):a(j)=a(j-1):a(j-1)=t Else If a(j)>a(j-1)Then t=a(j):a(j)=a(j-1):a(j-1)=t End If Next j Next i bubble_sort=a