Sorting algorithms (sort array)
While it's no doubt been covered many times before, I was hoping to set up a nice repository of the various sorting algorithms in a single thread. So if you have VB6 code for a technique that isn't listed, please post it.
To keep the code as simple as possible, assume we are sorting single-dimension typed arrays. Your code can work for string or numeric arrays; it will be up to the reader to make any necessary conversions.
I'll start us off with the old standby, the QuickSort:
Code:
' Omit plngLeft & plngRight; they are used internally during recursion
Public Sub QuickSortLong(ByRef plngArray() As Long, Optional ByVal plngLeft As Long, Optional ByVal plngRight As Long)
Dim lngFirst As Long
Dim lngMid As Long
Dim lngLast As Long
Dim lngSwap As Long
If plngRight = 0 Then
plngLeft = LBound(plngArray)
plngRight = UBound(plngArray)
End If
lngFirst = plngLeft
lngLast = plngRight
lngMid = plngArray((plngLeft + plngRight) \ 2)
Do
Do While plngArray(lngFirst) < lngMid And lngFirst < plngRight
lngFirst = lngFirst + 1
Loop
Do While lngMid < plngArray(lngLast) And lngLast > plngLeft
lngLast = lngLast - 1
Loop
If lngFirst <= lngLast Then
lngSwap = plngArray(lngFirst)
plngArray(lngFirst) = plngArray(lngLast)
plngArray(lngLast) = lngSwap
lngFirst = lngFirst + 1
lngLast = lngLast - 1
End If
Loop Until lngFirst > lngLast
If plngLeft < lngLast Then QuickSortLong plngArray, plngLeft, lngLast
If lngFirst < plngRight Then QuickSortLong plngArray, lngFirst, plngRight
End Sub