VBA array sort function?

后端 未结 13 1958
北荒
北荒 2020-11-22 05:28

I\'m looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice.

<
13条回答
  •  礼貌的吻别
    2020-11-22 05:51

    Heapsort implementation. An O(n log(n)) (both average and worst case), in place, unstable sorting algorithm.

    Use with: Call HeapSort(A), where A is a one dimensional array of variants, with Option Base 1.

    Sub SiftUp(A() As Variant, I As Long)
        Dim K As Long, P As Long, S As Variant
        K = I
        While K > 1
            P = K \ 2
            If A(K) > A(P) Then
                S = A(P): A(P) = A(K): A(K) = S
                K = P
            Else
                Exit Sub
            End If
        Wend
    End Sub
    
    Sub SiftDown(A() As Variant, I As Long)
        Dim K As Long, L As Long, S As Variant
        K = 1
        Do
            L = K + K
            If L > I Then Exit Sub
            If L + 1 <= I Then
                If A(L + 1) > A(L) Then L = L + 1
            End If
            If A(K) < A(L) Then
                S = A(K): A(K) = A(L): A(L) = S
                K = L
            Else
                Exit Sub
            End If
        Loop
    End Sub
    
    Sub HeapSort(A() As Variant)
        Dim N As Long, I As Long, S As Variant
        N = UBound(A)
        For I = 2 To N
            Call SiftUp(A, I)
        Next I
        For I = N To 2 Step -1
            S = A(I): A(I) = A(1): A(1) = S
            Call SiftDown(A, I - 1)
        Next
    End Sub
    

提交回复
热议问题