サブルーチンとして次を定義しておく。
Sub QuickSort(arr As Variant, firstIndex As Long, lastIndex As Long)
Dim pivot As Variant
Dim pivotIndex As Long
Dim leftIndex As Long
Dim rightIndex As Long
If firstIndex < lastIndex Then
pivot = arr(lastIndex)
pivotIndex = firstIndex - 1
leftIndex = firstIndex
For rightIndex = firstIndex To lastIndex - 1
If arr(rightIndex) <= pivot Then
pivotIndex = pivotIndex + 1
Swap arr(pivotIndex), arr(rightIndex)
End If
Next rightIndex
pivotIndex = pivotIndex + 1
Swap arr(pivotIndex), arr(lastIndex)
Call QuickSort(arr, firstIndex, pivotIndex - 1)
Call QuickSort(arr, pivotIndex + 1, lastIndex)
End If
End Sub
Sub Swap(ByRef a As Variant, ByRef b As Variant)
Dim temp As Variant
temp = a
a = b
b = temp
End Sub
呼び出しは次のようにする
Dim arr As Variant
arr = Array(4, 2, 3, 1, 5)
Call QuickSort(arr, 0, UBound(arr))