AccessVBA/クイックソート

AccessVBA/クイックソート

クイックソート

'配列の要素を交換
Private Sub AcSwap(tAy() As Long, ni1 As Integer, ni2 As Integer)
    Dim nTemp As Long

    nTemp = tAy(ni2)
    tAy(ni2) = tAy(ni1)
    tAy(ni1) = nTemp
End Sub

'クイックソート
Sub AcQsort(tAry() As Long, nLeft As Integer, nRight As Integer)
    Dim i As Integer
    Dim j As Integer
    Dim nmid As Long
    Dim npivot As Long
    
    If nLeft < nRight Then
        i = nLeft
        j = nRight
        '配列の中央
        nmid = (nLeft + nRight) \ 2
        '基準値
        npivot = tAry(nmid)
        
        Do
            Do While tAry(j) > npivot
                j = j - 1
            Loop
            Do While tAry(i) < npivot
                i = i + 1
            Loop
            If i <= j Then
                AcSwap tAry(), i, j
                i = i + 1
                j = j - 1
            End If
        Loop Until i > j
        
        If j > nmid Then
            AcQsort tAry(), i, nRight
            AcQsort tAry(), nLeft, j
        Else
            AcQsort tAry(), nLeft, j
            AcQsort tAry(), i, nRight
        End If
    End If

End Sub