|
这是快速排序代码 你要得到位置数组很简单 修改如下 传入位置数组即可 test函数中是调用方式和测试结果- Option Explicit
- 'Dim brr() '位置数组
- Public Sub QSort(MyArray, brr, Lboundx, Uboundx, Optional TF As Boolean = True)
- 'TF=TRUE 升序
- 'TF=FALSE 降序
- Dim i, j, x, Y, arr()
- i = Lboundx
- j = Uboundx
- '找出数组的中点
- x = MyArray((Lboundx + Uboundx) / 2)
- While (i <= j)
-
- If TF Then '※正排序
- '找出比中点大的数
- While (MyArray(i) < x And i < Uboundx)
- i = i + 1
- Wend
- '找出比中点小的数
- While (x < MyArray(j) And j > Lboundx)
- j = j - 1
- Wend
-
-
- Else '※逆排序
- '找出比中点大的数
- While (MyArray(i) > x And i < Uboundx)
- i = i + 1
- Wend
- '找出比中点小的数
- While (x > MyArray(j) And j > Lboundx)
- j = j - 1
- Wend
- End If
-
- '互换这两个数
- If (i <= j) Then
-
- Y = MyArray(i): MyArray(i) = MyArray(j): MyArray(j) = Y '数值换位
- Y = brr(i): brr(i) = brr(j): brr(j) = Y '位置换位
- i = i + 1
- j = j - 1
- End If
- '用于指明重复次数的全局变量
- 'gIterations = gIterations + 1
- Wend
- '未完成时递归调用
- If (Lboundx < j) Then QSort MyArray, brr, Lboundx, j, TF
- If (i < Uboundx) Then QSort MyArray, brr, i, Uboundx, TF
- End Sub
- Private Sub Test()
-
- Dim i&, j&, k&, arr, brr
- arr = [{5,3,7,1,8}]
- ReDim brr(1 To 5) '位置数组
- For i = 1 To 5
- brr(i) = i '准备位置数组
- Next
- QSort arr, brr, 1, 5
- For i = 1 To UBound(arr) '输出排序结果和位置
- Debug.Print arr(i), brr(i)
- Next
- End Sub
复制代码 |
|