1、冒泡排序
规则:它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
冒泡排序算法的运作如下:(从后往前)
1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3、针对所有的元素重复以上的步骤,除了最后一个。
4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。[1]
Private Sub Command1_Click()
Dim a
Dim b As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
a = Array(6, 3, 7, 8, 2, 1)
Print "排序前为";
For i = 1 To 6
Print a(i);
Next i
For i = 1 To 5
For j = 1 To 6 - i
Print "比较 下标 j=";j;" 与 下标 j+1=";j+1
If a(j) > a(j + 1) Then
Print
Print "下标 j=";j;" 大于 下标 j+1=";j+1;" 的元素"
b = a(j + 1)
a(j + 1) = a(j)
a(j) = b
Print
Print "交换位置"
End If
Print
For k = 1 To 6
Print a(k);
Next k
Next j
Next i
End Sub
注意注意
2、直接选择排序
原理:每次从待排序的记录中选出最大/最小的数,放入已排好序的子文件中,直到全部记录完成。
从小到大排序
Dim a
Dim temp As Integer
Dim i As Integer
Dim j As Integer
Dim z As Integer
a = Array(6, 3, 7, 8, 2, 1)
Print "排序前为";
For i = 1 To 6
Print a(i);
Next i
Dim min As Integer //最小元素的值
Dim k As Integer //最小元素的小标
For i = 1 To 4
k=i
min=a(k)
For j = i+1 To 5
Print
Print " k=";k;" min =";min ;" j=";j
If min > a(j) Then
k=j
min=a(k)
End If
Print
Print "比较完成后 最小元素下标 为: k=";k;" 最小元素值为 min =";min
Next j
Print
Print "交换元素位置 i ";i;" k ": k
temp = a(i)
a(i) = min
a(k) = temp
Print
For z = 1 To 6
Print a(z);
Next z
Next i
End Sub
从大到小排序
Dim a
Dim temp As Integer
Dim i As Integer
Dim j As Integer
Dim z As Integer
a = Array(6, 3, 7, 8, 2, 1)
Print "排序前为";
For i = 1 To 6
Print a(i);
Next i
Dim max As Integer //最大元素的值
Dim k As Integer //最大元素的小标
For i = 5 To 2
k=0
min=a(k)
For j = 1 To i
Print
Print " k=";k;" max =";max ;" j=";j
If max < a(j) Then
k=j
max=a(k)
End If
Print
Print "比较完成后 最大元素下标 为: k=";k;" 最大元素值为 max =";max
Next j
Print
Print "交换元素位置 i ";i;" k ": k
temp = a(i)
a(i) = min
a(k) = temp
Print
For z = 1 To 6
Print a(z);
Next z
Next i
End Sub
注意注意
3、插入排序
原理:每次执行,把后面的数插入到前面已经排序好的数组中,直到最后一个完成。
Dim a
Dim temp As Integer
Dim i As Integer
Dim j As Integer
Dim z As Integer
a = Array(6, 3, 7, 8, 2, 1)
Print "排序前为";
For i = 1 To 6
Next i
For i = 2 To 5
For j = 1 To i-1
If a(i) < a(j) Then
temp = a(i)
For k=i to j+1 step -1
a(k)=a(k-1)
next k
a(j)=temp
j=i
End If
Next j
temp = a(i)
a(i) = min
a(k) = temp
Print
For z = 1 To 6
Print a(z);
Next z
Next i
讲解