Tip

Recursive Quick Sort Script

Recursive Quick Sort script
Sub quicksort (lngLbound As Long,lngUbound As Long, varSortArray As Variant)
'Pass the lower bound of the array to lngLbound, the upper bound of the array
to lngUbound and the array to varSortArray.
Dim varValue1 As Variant
Dim varValue2 As Variant
Dim lngTmpLbound As Long
Dim lngTmpUbound As Long

If lngUbound > lngLbound Then 'If there's nothing to sort, jump out
varValue1 = varSortArray(lngLbound) 'Initialize boundaries, nominate
a value to sort
lngTmpUbound = lngUbound
lngTmpLBound = lngLbound

While (lngTmpLBound < lngTmpUbound) 'Repeat until lngTmpLBound and
lngTmpUbound "meet in the middle"
While (varSortArray(lngTmpLBound) <= varValue1 And lngTmpLBound
< lngUbound) 'Push in the boundaries while data is sorted
lngTmpLBound = lngTmpLBound + 1
Wend
While (varSortArray(lngTmpUbound) > varValue1)
lngTmpUbound = lngTmpUbound - 1
Wend
If lngTmpLBound < lngTmpUbound Then 'If there is data between
lngTmpLBound and lngTmpUbound something is out of order - swap it
varValue2 = varSortArray(lngTmpLBound)
varSortArray(lngTmpLBound) = varSortArray(lngTmpUbound)
varSortArray(lngTmpUbound) = varValue2
End If
Wend

varValue2 = varSortArray(lngLbound) 'Swap the nominated and bottom
values - why we came here
varSortArray(lngLbound) = varSortArray(lngTmpUbound)
varSortArray(lngTmpUbound) = varValue2
Call quicksort (lngLbound, lngTmpUbound - 1, varSortArray) 'Recurse
and sort data either side of upper bound
Call quicksort ((lngTmpUbound + 1), lngUbound, varSortArray)
End If
End Sub

This was first published in November 2000

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.