2) 冒泡法排序
選擇排序法在每一輪排序時(shí)找最值元素的下標(biāo),出了內(nèi)循環(huán)(一輪排序結(jié)束),再交換最小數(shù)的位置;而冒泡法在每一輪排序時(shí)將相鄰的數(shù)比較,當(dāng)次序不對(duì)就交換位置,出了內(nèi)循環(huán),最值數(shù)已經(jīng)冒出。
譬如:
8 6 9 3 2 7
8 6 9 3 2 7
8 6 9 2 3 7
8 6 2 9 3 7
8 2 6 9 3 7
2 8 6 9 3 7
….
2 3 8 6 9 7
….
2 3 6 8 7 9
….
2 3 6 7 8 9
….
2 3 6 7 8 9
程序代碼如下:
Private Sub mpPaiXu(a() As Double, sheng As Boolean)
'a為需要排序的數(shù)組,sheng為T(mén)rue則為升序排列,為False,則為降序排列。
Dim i As Integer, j As Integer
Dim temp As Double
Dim m As Integer
For i = LBound(a) To UBound(a) - 1 '進(jìn)行n-1輪比較
For j = UBound(a) To i + 1 Step -1 '從n到i個(gè)元素兩兩進(jìn)行比較
If sheng Then '若次序不對(duì),馬上進(jìn)行交換
If a(j) < a(j - 1) Then
temp = a(j)
a(j) = a(j - 1)
a(j - 1) = temp
End If
Else
If a(j) > a(j - 1) Then
temp = a(j)
a(j) = a(j - 1)
a(j - 1) = temp
End If
End If
Next j '出了內(nèi)循環(huán),一輪排序結(jié)束
'最值元素冒到最上邊
Next i
End Sub
調(diào)用該過(guò)程代碼基本同上。
希望與更多計(jì)算機(jī)等級(jí)考試的網(wǎng)友交流,請(qǐng)進(jìn)入計(jì)算機(jī)等級(jí)考試論壇
更多信息請(qǐng)?jiān)L問(wèn):考試吧計(jì)算機(jī)等級(jí)考試欄目