' quick sort Private Function Partition(ByRef A() As Variant, ByVal Lb As Long, ByVal Ub As Long) _ As Long Dim t As Variant Dim pivot As Variant Dim i As Long Dim j As Long Dim p As Long ' partition array[lb..ub] ' select pivot and exchange with 1st element p = Lb + (Ub - Lb) \ 2 pivot = A(p) A(p) = A(Lb) ' sort Lb+1 .. Ub based on pivot i = Lb j = Ub + 1 Do Do j = j - 1 While j > i And A(j) > pivot Do i = i + 1 While i < j And A(i) < pivot If i >= j Then Exit Do ' swap A(i), A(j) t = A(i) A(i) = A(j) A(j) = t Loop ' pivot belongs in A(j) A(Lb) = A(j) A(j) = pivot Partition = j End Function Public Sub QuickSort(ByRef A() As Variant, ByVal Lb As Long, ByVal Ub As Long) Dim m As Long ' sort array A(lb..ub) Do While Lb < Ub ' quickly sort short lists If (Ub - Lb <= 12) Then Call InsertSort(A, Lb, Ub) Exit Sub End If ' partition into two segments m = Partition(A, Lb, Ub) ' sort the smallest partition to minimize stack requirements If m - Lb <= Ub - m Then Call QuickSort(A, Lb, m - 1) Lb = m + 1 Else Call QuickSort(A, m + 1, Ub) Ub = m - 1 End If Loop End Sub