Skip to content

Instantly share code, notes, and snippets.

@neelsg
Created November 3, 2014 09:29
Show Gist options
  • Save neelsg/4ba507e6d0f389f58350 to your computer and use it in GitHub Desktop.
Save neelsg/4ba507e6d0f389f58350 to your computer and use it in GitHub Desktop.
Quicksort implementation in VBScript / VBA
Sub QuickSort(ByRef ThisArray)
'Sort an array alphabetically
Dim LowerBound, UpperBound
LowerBound = LBound(ThisArray)
UpperBound = UBound(ThisArray)
QuickSortRecursive ThisArray, LowerBound, UpperBound
End Sub
Sub QuickSortRecursive(ByRef ThisArray, ByVal LowerBound, ByVal UpperBound)
'Approximate implementation of https://en.wikipedia.org/wiki/Quicksort
Dim PivotValue, LowerSwap, UpperSwap, TempItem
'Zero or 1 item to sort
If UpperBound - LowerBound < 1 Then Exit Sub
'Only 2 items to sort
If UpperBound - LowerBound = 1 Then
If ThisArray(LowerBound) > ThisArray(UpperBound) Then
TempItem = ThisArray(LowerBound)
ThisArray(LowerBound) = ThisArray(UpperBound)
ThisArray(UpperBound) = TempItem
End If
Exit Sub
End If
'3 or more items to sort
PivotValue = ThisArray(Int((LowerBound + UpperBound) / 2))
ThisArray(Int((LowerBound + UpperBound) / 2)) = ThisArray(LowerBound)
LowerSwap = LowerBound + 1
UpperSwap = UpperBound
Do
'Find the right LowerSwap
While LowerSwap < UpperSwap And ThisArray(LowerSwap) <= PivotValue
LowerSwap = LowerSwap + 1
Wend
'Find the right UpperSwap
While LowerBound < UpperSwap And ThisArray(UpperSwap) > PivotValue
UpperSwap = UpperSwap - 1
Wend
'Swap values if LowerSwap is less than UpperSwap
If LowerSwap < UpperSwap then
TempItem = ThisArray(LowerSwap)
ThisArray(LowerSwap) = ThisArray(UpperSwap)
ThisArray(UpperSwap) = TempItem
End If
Loop While LowerSwap < UpperSwap
ThisArray(LowerBound) = ThisArray(UpperSwap)
ThisArray(UpperSwap) = PivotValue
'Recursively call function
'2 or more items in first section
If LowerBound < (UpperSwap - 1) Then QuickSortRecursive ThisArray, LowerBound, UpperSwap - 1
'2 or more items in second section
If UpperSwap + 1 < UpperBound Then QuickSortRecursive ThisArray, UpperSwap + 1, UpperBound
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment