小吳為了探究冒泡排序過(guò)程中數(shù)據(jù)的“移動(dòng)”情況,編寫(xiě)了一個(gè)VB程序,功能如下:在列表框List1中顯示排序前數(shù)據(jù)(存儲(chǔ)在數(shù)組a中),在文本框Text1中輸入初始位置(即下標(biāo)值),單擊“排序”按鈕Command1后,在標(biāo)簽Label1中顯示指定初始位置的數(shù)據(jù)在排序過(guò)程中的位置變化情況,排序后的數(shù)據(jù)顯示在列表框List2中。程序運(yùn)行界面如圖所示。 實(shí)現(xiàn)上述功能的VB程序如下,但加框處代碼有錯(cuò),請(qǐng)改正。 Dim a(1To 8)As Integer Dim n As Integer Private Sub Form_Load ( ) 'n=8,排序前的8個(gè)數(shù)據(jù)存儲(chǔ)在數(shù)組a中,并在列表框Listl中顯示 '代碼略 End Sub Private Sub Command1_Click ( ) Dim i As Integer,j As Integer,k As Integer Dim pos As Integer'變量pos存儲(chǔ)指定數(shù)據(jù)的位置(即下標(biāo)值) Dim s As String'變量s存儲(chǔ)pos變化情況 s=Text1.Text pos=Val(Text1.Text) For i=1To n-1 For j=n To i+1Step-1 If a(j)<a(j-1)Then ‘(1) a(j-1)=a(j) a(j)=k '如果pos位置的數(shù)據(jù)參與交換,則更新pos值,記錄pos變化情況 If pos=j Then pos=j-1 s=s+”→”+Str(pos) ‘(2) pos=j s=s+”→”+Str(pos) End If End If Next j Next i Label1.Caption=”位置變化情況:”+s For i=1To n List2.AddItem Str(a(i)) Next i End Sub
是待排序的數(shù)據(jù),數(shù)據(jù)從a(1)開(kāi)始存放;整數(shù)型參數(shù)n表示傳入的數(shù)組長(zhǎng)度,該函數(shù)的返回值也是一個(gè)整數(shù)型數(shù)組.所以調(diào)用此函數(shù)實(shí)現(xiàn)排序非常方便: 比如有一個(gè)整數(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