2) 冒泡法排序
選擇排序法在每一輪排序時找最值元素的下標,出了內(nèi)循環(huán)(一輪排序結(jié)束),再交換最小數(shù)的位置;而冒泡法在每一輪排序時將相鄰的數(shù)比較,當次序不對就交換位置,出了內(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為True則為升序排列,為False,則為降序排列。
Dim i As Integer, j As Integer
Dim temp As Double
Dim m As Integer
For i = LBound(a) To UBound(a) - 1 '進行n-1輪比較
For j = UBound(a) To i + 1 Step -1 '從n到i個元素兩兩進行比較
If sheng Then '若次序不對,馬上進行交換
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)用該過程代碼基本同上。
希望與更多計算機等級考試的網(wǎng)友交流,請進入計算機等級考試論壇
更多信息請訪問:考試吧計算機等級考試欄目