Access/VBA Library

QuickSort

Rescursive procedure to sort an array.

Syntax

QuickSort( vArray [, indexLow] [, indexHigh] )
Parameters
Name Type Description
vArray Variant Required. The array to be sorted.
indexLow Long Optional. Lowest element index of the array to be sorted.
Default: -1
indexHigh Long Optional. Highest element index of the arrat to be sorted.
Default: -1
Code
Public Sub QuickSort(vArray As Variant, _
                     Optional ByVal indexLow As Long = -1, _
                     Optional ByVal indexHigh As Long = -1)

  Dim pivot As Variant
  Dim tmpSwap As Variant
  Dim tmpLow As Long
  Dim tmpHi As Long

  If indexLow = -1 Then indexLow = LBound(vArray)
  If indexHigh = -1 Then indexHigh = UBound(vArray)
  
  tmpLow = indexLow
  tmpHi = indexHigh

  pivot = vArray((indexLow + indexHigh) \ 2)

  While (tmpLow <= tmpHi)

     While (vArray(tmpLow) < pivot And tmpLow < indexHigh)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > indexLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If

  Wend

  If (indexLow < tmpHi) Then QuickSort vArray, indexLow, tmpHi
  If (tmpLow < indexHigh) Then QuickSort vArray, tmpLow, indexHigh

End Sub

Arraytag:Array

Remarks

  • Just call this procedure with only vArray specified.