A VBA implementation of Tony Hoare’s famous recursive divide-and-conquer sorting algorithm from 1959. The array is sorted in-place, i.e. through swapping of elements without using any auxiliary data structure.
Table of Contents
Function
VBASub QuickSort(arr As Variant, arrLbd As Long, arrUbd As Long) Dim tmpLow As Long, tmpHi As Long Dim pivot As Variant, swap As Variant tmpLow = arrLbd tmpHi = arrUbd pivot = arr((arrLbd + arrUbd) \ 2) While tmpLow <= tmpHi While arr(tmpLow) < pivot And tmpLow < arrUbd tmpLow = tmpLow + 1 Wend While pivot < arr(tmpHi) And tmpHi > arrLbd tmpHi = tmpHi - 1 Wend If tmpLow <= tmpHi Then swap = arr(tmpLow) arr(tmpLow) = arr(tmpHi) arr(tmpHi) = swap tmpLow = tmpLow + 1 tmpHi = tmpHi - 1 End If Wend If arrLbd < tmpHi Then QuickSort arr, arrLbd, tmpHi If tmpLow < arrUbd Then QuickSort arr, tmpLow, arrUbd End Sub
Parameters
Name | Optional/ Required | Data type | Description |
arr | Required | Array | The array to be sorted. Must be indexed-based and one-dimensional. |
arrLbd | Required | Integer | The lower index bound of the input array. Typically, the lower bound should be set to zero, but if set higher, only the values in the array from the set index and above will be sorted. |
arrUbd | Required | Integer | The upper index bound of the input array. Typically, the upper bound should be set to the number of elements in the array – 1, but if set lower, only the values in the array from the set index and below will be sorted. |
Usage example
VBASub TestQuickSort() Dim arr As Variant, vItem As Variant arr = Array(5, 3, 1, 2) Call QuickSort(arr, LBound(arr), UBound(arr)) For Each vItem In arr Debug.Print vItem Next vItem End Sub