VBA:Quicksort Descending

时间:2016-06-14 21:27:18

标签: vba quicksort

如何将this转换为降序?我尝试了一下它可以处理一个较小的样本,但我只是想确保我把它正确地解决了。这是我original的编辑版本:

Private Sub QuickSortByAge(arr() As Integer, inLow As Integer, inHi As Integer)
    Dim pivot   As Integer
    Dim tmpSwap As Integer
    Dim tmpLow  As Integer
    Dim tmpHi   As Integer

    tmpLow = inLow
    tmpHi = inHi

    pivot = arr((inLow + inHi) \ 2)

    While (tmpLow <= tmpHi)
        While (arr(tmpLow) > pivot And tmpLow < inHi) 'converted sign
            tmpLow = tmpLow + 1
        Wend

        While (pivot > arr(tmpHi) And tmpHi > inLow) 'converted sign              
            tmpHi = tmpHi - 1
        Wend

        If (tmpLow <= tmpHi) Then
            tmpSwap = arr(tmpLow)
            arr(tmpLow) = arr(tmpHi)
            arr(tmpHi) = tmpSwap
            tmpLow = tmpLow + 1
            tmpHi = tmpHi - 1
        End If

    Wend

    If (inLow < tmpHi) Then QuickSortByAge arr, inLow, tmpHi
    If (tmpLow < inHi) Then QuickSortByAge arr, tmpLow, inHi

End Sub

1 个答案:

答案 0 :(得分:0)

algorythm是原始的升序排序。

添加这些线以逆转流程。

tmpLow = inLow
tmpHi = inHi

我创建了一个测试来填充arr(1000000),然后使用QuickSortByAge对其进行排序。当它崩溃时,我检查打开了局部变量窗口,发现tmpHi的值是16385.我机器上的最大阵列大小是16384。

Sub Test()

    Dim arr(16384) As Integer

    For i = 0 To UBound(arr)
        arr(i) = Int((Rnd * 1000) + 1)
    Next

    QuickSortByAge arr, 0, UBound(arr)

    For Each c In arr
        Debug.Print c
    Next

End Sub

Public Sub QuickSortByAge(arr() As Integer, inLow As Integer, inHi As Integer, Optional bDescending As Boolean)
    Dim pivot As Integer
    Dim tmpSwap As Integer
    Dim tmpLow As Integer
    Dim tmpHi As Integer


        tmpLow = inLow
        tmpHi = inHi


    pivot = arr((inLow + inHi) \ 2)

    While (tmpLow <= tmpHi)
        While (arr(tmpLow) > pivot And tmpLow < inHi)    'converted sign
            tmpLow = tmpLow + 1
        Wend

        While (pivot > arr(tmpHi) And tmpHi > inLow)    'converted sign
            tmpHi = tmpHi - 1
        Wend

        If (tmpLow <= tmpHi) Then
            tmpSwap = arr(tmpLow)
            arr(tmpLow) = arr(tmpHi)
            arr(tmpHi) = tmpSwap
            tmpLow = tmpLow + 1
            tmpHi = tmpHi - 1
        End If

    Wend

    If (inLow < tmpHi) Then QuickSortByAge arr, inLow, tmpHi, bDescending
    If (tmpLow < inHi) Then QuickSortByAge arr, tmpLow, inHi, bDescending

End Sub