VBA排序地十种算法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
在使用VBA进行写程序时,经常会做排序,下面将会给出一些常用的排序算法的实现,方便大家写程序参考,若代码中出现了错误,欢迎高手指正。
主要算法有:
1、(冒泡排序)Bubble sort
2、(选择排序)Selection sort
3、(插入排序)Insertion sort
4、(快速排序)Quick sort
5、(合并排序)Merge sort
6、(堆排序)Heap sort
7、(组合排序)Comb Sort
8、(希尔排序)Shell Sort
9、(基数排序)Radix Sort
10、Shaker Sort
第一种(冒泡排序)Bubble sort
Public Sub BubbleSort(ByRef lngArray() As Long)
Dim iOuter As Long
Dim iInner As Long
Dim iLBound As Long
Dim iUBound As Long
Dim iTemp As Long
iLBound = LBound(lngArray)
iUBound = UBound(lngArray)
'冒泡排序
For iOuter = iLBound To iUBound - 1
For iInner = iLBound To iUBound - iOuter - 1
'比较相邻项
If lngArray(iInner) > lngArray(iInner + 1) Then
'交换值
iTemp = lngArray(iInner)
lngArray(iInner) = lngArray(iInner + 1)
lngArray(iInner + 1) = iTemp
End If
Next iInner
Next iOuter
End Sub
2、(选择排序)Selection sort
1.Public Sub SelectionSort(ByRef lngArray() As Long)
2.Dim iOuter As Long
3.Dim iInner As Long
4.Dim iLBound As Long
5.Dim iUBound As Long
6.Dim iTemp As Long
7.Dim iMax As Long
8.
9.iLBound = LBound(lngArray)
10.iUBound = UBound(lngArray)
11.
12.'选择排序
13.For iOuter = iUBound To iLBound + 1 Step -1
14.
15.iMax = 0
16.
17.'得到最大值得索引
18.For iInner = iLBound To iOuter
19.If lngArray(iInner) > lngArray(iMax) Then iMax = iInner
20.Next iInner
21.
22.'值交换
23.iTemp = lngArray(iMax)
24.lngArray(iMax) = lngArray(iOuter)
25.lngArray(iOuter) = iTemp
26.
27.Next iOuter
28.End Sub
复制代码
第三种(插入排序)Insertion sort
1.Public Sub InsertionSort(ByRef lngArray() As Long)
2.Dim iOuter As Long
3.Dim iInner As Long
4.Dim iLBound As Long
5.Dim iUBound As Long
6.Dim iTemp As Long
7.
8.iLBound = LBound(lngArray)
9.iUBound = UBound(lngArray)
10.
11.For iOuter = iLBound + 1 To iUBound
12.
13.'取得插入值
14.iTemp = lngArray(iOuter)
15.
16.'移动已经排序的值
17.For iInner = iOuter - 1 To iLBound Step -1
18.If lngArray(iInner) <= iTemp Then Exit For
19.lngArray(iInner + 1) = lngArray(iInner)
20.Next iInner
21.
22.'插入值
23.lngArray(iInner + 1) = iTemp
24.Next iOuter
25.End Sub
复制代码
第四种(快速排序)Quick sort
1.Public Sub QuickSort(ByRef lngArray() As Long)
2.Dim iLBound As Long
3.Dim iUBound As Long
4.Dim iTemp As Long
5.Dim iOuter As Long
6.Dim iMax As Long
7.
8.iLBound = LBound(lngArray)
9.iUBound = UBound(lngArray)
10.
11.'若只有一个值,不排序
12.If (iUBound - iLBound) Then
13.For iOuter = iLBound To iUBound
14.If lngArray(iOuter) > lngArray(iMax) Then iMax = iOuter
15.Next iOuter
16.
17.iTemp = lngArray(iMax)
18.lngArray(iMax) = lngArray(iUBound)
19.lngArray(iUBound) = iTemp
20.
21.'开始快速排序
22.InnerQuickSort lngArray, iLBound, iUBound
23.End If
24.End Sub
25.
26.Private Sub InnerQuickSort(ByRef lngArray() As Long, ByVal iLeftEnd As Long, ByVal
iRightEnd As Long)
27.Dim iLeftCur As Long
28.Dim iRightCur As Long
29.Dim iPivot As Long