'The following code can be used to rapdily sort a 1d array.
'Purpose : Sorts a 1D array.
'Inputs : avValues. The array to sort
' [lLowerBound] The lLowerBound of Array. NOT REQUIRED (USED IN RECURSIVE LOOP)
' [lUpperBound] The lUpperBound of Array. NOT REQUIRED (USED IN RECURSIVE LOOP)
' [bSortDescending ] If True sorts the array in descending order. Defaults to ascending.
'Outputs : avValues is sorted.
'Notes : The optional parameters are not required to be passed in.
' They are only required for the subsequent recursive calls.
' This type of sorting is much faster than "Bubble Sorting", especially
' if your items are order randomly.
Sub Array1DSort(ByRef avValues As Variant, Optional lLowerBound As Long, Optional lUpperBound As Long, Optional ByVal bSortDescending As Boolean = False)
Dim lTestLower As Long, lTestUpper As Long, vThisItem As Variant, vThisValue As Variant
If lLowerBound = 0 Then
lLowerBound = LBound(avValues)
End If
If lUpperBound = 0 Then
lUpperBound = UBound(avValues)
End If
lTestLower = lLowerBound
lTestUpper = lUpperBound
vThisItem = avValues((lLowerBound + lUpperBound) / 2)
If bSortDescending Then
Do While (lTestLower <= lTestUpper)
Do While (avValues(lTestLower) > vThisItem And lTestLower < lUpperBound)
lTestLower = lTestLower + 1
Loop
Do While (vThisItem > avValues(lTestUpper) And lTestUpper > lLowerBound)
lTestUpper = lTestUpper - 1
Loop
If (lTestLower <= lTestUpper) Then
vThisValue = avValues(lTestLower)
avValues(lTestLower) = avValues(lTestUpper)
avValues(lTestUpper) = vThisValue
lTestLower = lTestLower + 1
lTestUpper = lTestUpper - 1
End If
Loop
Else
Do While (lTestLower <= lTestUpper)
Do While (avValues(lTestLower) < vThisItem And lTestLower < lUpperBound)
lTestLower = lTestLower + 1
Loop
Do While (vThisItem < avValues(lTestUpper) And lTestUpper > lLowerBound)
lTestUpper = lTestUpper - 1
Loop
If (lTestLower <= lTestUpper) Then
vThisValue = avValues(lTestLower)
avValues(lTestLower) = avValues(lTestUpper)
avValues(lTestUpper) = vThisValue
lTestLower = lTestLower + 1
lTestUpper = lTestUpper - 1
End If
Loop
End If
If (lLowerBound < lTestUpper) Then
Array1DSort avValues, lLowerBound, lTestUpper, bSortDescending
End If
If (lTestLower < lUpperBound) Then
Array1DSort avValues, lTestLower, lUpperBound, bSortDescending
End If
End Sub