VBA array sort function?

后端 未结 13 1953
北荒
北荒 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 06:03

    Explanation in German but the code is a well-tested in-place implementation:

    Private Sub QuickSort(ByRef Field() As String, ByVal LB As Long, ByVal UB As Long)
        Dim P1 As Long, P2 As Long, Ref As String, TEMP As String
    
        P1 = LB
        P2 = UB
        Ref = Field((P1 + P2) / 2)
    
        Do
            Do While (Field(P1) < Ref)
                P1 = P1 + 1
            Loop
    
            Do While (Field(P2) > Ref)
                P2 = P2 - 1
            Loop
    
            If P1 <= P2 Then
                TEMP = Field(P1)
                Field(P1) = Field(P2)
                Field(P2) = TEMP
    
                P1 = P1 + 1
                P2 = P2 - 1
            End If
        Loop Until (P1 > P2)
    
        If LB < P2 Then Call QuickSort(Field, LB, P2)
        If P1 < UB Then Call QuickSort(Field, P1, UB)
    End Sub
    

    Invoked like this:

    Call QuickSort(MyArray, LBound(MyArray), UBound(MyArray))
    

提交回复
热议问题