转自(http://www.cnblogs.com/IDqq/archive/2006/04/04/366688.html)
1 冒泡排序
冒泡排序虽然性能不高,但好歹是一种稳定的排序。在要求排序结果稳定,或者性能问题不很突出(比如给只含少量元素的小数组排序)的时候,用起来还是比较方便。下面给出一个较为通用的实现。
' 升序冒泡Private Sub Sort(ByRef ary As Variant)Dim i As LongDim j As LongDim vTmp As VariantFor i = 0 To UBound(ary) - 1For j = i + 1 To UBound(ary)If ary(i) > ary(j) ThenvTmp = ary(i)ary(i) = ary(j)ary(j) = vTmpEnd IfNextNext End Sub
2 快速排序
快排可以说是应用最为广泛的一种排序了。快排的平均排序性能最好,但不是稳定的排序。
' 升序快排Private Sub QuickSort(ByRef ary As Variant)Call QSort(ary, 0, UBound(ary))End Sub' 子函数:对子数组递归排序Private Sub QSort(ByRef ary As Variant, ByVal lLow As Long, ByVal lHigh As Long)Dim lPivot As LongIf lLow < lHigh ThenlPivot = Part(ary, lLow, lHigh)Call QSort(ary, lLow, lPivot - 1)Call QSort(ary, lPivot + 1, lHigh)End If End Sub' 子函数:选定ary(lLow)为枢轴,把数组分成比枢轴大/小的两部分 Private Function Part(ByRef ary As Variant, ByVal lLow As Long, ByVal lHigh As Long) As LongDim vPivot As VariantvPivot = ary(lLow)Do While lLow < lHighDo While lLow < lHigh And ary(lHigh) >= vPivotlHigh = lHigh - 1LoopIf lLow = lHigh Then Exit Doary(lLow) = ary(lHigh)Do While lLow < lHigh And ary(lLow) <= vPivotlLow = lLow + 1LoopIf lLow = lHigh Then Exit Doary(lHigh) = ary(lLow)Loopary(lLow) = vPivotPart = lLow End Function
3 用法示例
Dim ary As Variant Dim byt As Byte() ary = Array(1, 3, 2, 5, 12, 8, 7, 9) Sort ary byt = StrConv("AZCDI", vbFromUnicode) Sort byt ary = Array(8, 1, 3, 2, 5, 12, 7, 9) QuickSort ary
转载于:https://www.cnblogs.com/Spacecup/p/3865037.html