 |
冒泡法排序 选择排序法在每一轮排序时找最值元素的下标,出了内循环(一轮排序结束),再交换最小数的位置;而冒泡法在每一轮排序时将相邻的数比较,当次序不对就交换位置,出了内循环,最值数已经冒出。 譬如: 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为需要排序的数组,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 '出了内循环,一轮排序结束 '最值元素冒到最上边 Next i End Sub 调用该过程代码基本同上。 2、实战练习
1) 补充代码 下面是一个采用拉锯式排序法对数组元素按升序进行排序的程序,所谓“拉锯式排序法”是这一遍把最小的元素从下到上送到最上的位置,下一遍则是从上到下把最大的元素送到最下的位置。 以下是片段: Option Base 1 Private Sub Command1_Click() Dim a(10) As Integer,i As Integer For i = 1 To 10 a(i) = Int(Rnd * 10)+1 Text1 = Text1 ; Str(a(i)) Next i Call shaker_sort(a) For i = 1 To 10 Text2 = Text2 ; 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 = (1) Do For (2) Step-1 If k(i=1)>k(i) Then t = k(i-1):k(i-1) = k(i):k(i) = t End If Next i (3) For i = c+1 To d If (4) Then t = k(i-1):k(i-1) = k(i):k(i) = t End If Next i d = d-1 Loop While (5) End Sub
2) 编程题 把文本框输入的字符串按降序添加到列表框中。
| |