Due to the high number of link only answers, including the accepted one, I will post a tested functional example of quicksort applied to an FSO files collection. The QuickSort
will work on any array of strings. I took the code from the link posted by Mitch Wheat in the accepted answer and cleaned it up.
Option Explicit
' Return an array containing the names of the
' files in the directory sorted alphabetically.
Public Function SortedFiles(ByVal dirPath As String) As String()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim listFolder As Object
Set listFolder = fso.GetFolder(dirPath)
' Make the list of names.
Dim fileCount As Long
fileCount = listFolder.Files.Count
Dim fileNames() As String
ReDim fileNames(1 To fileCount)
Dim i As Long
i = 1
Dim thisFile As Object
For Each thisFile In listFolder.Files
fileNames(i) = thisFile.Name
i = i + 1
Next thisFile
' Return the sorted list.
SortedFiles = QuickSort(fileNames, 1, fileCount)
End Function
' Use Quicksort to sort a list of strings.
'
' This code is from the book "Ready-to-Run
' Visual Basic Algorithms" by Rod Stephens.
' http://www.vb-helper.com/vba.htm
Public Function QuickSort(ByVal list As Variant, ByVal min As Long, ByVal max As Long) As String()
Dim midValue As String
Dim high As Long
Dim low As Long
Dim i As Long
Dim newList() As String
newList = list
' If there is 0 or 1 item in the list,
' this sublist is sorted.
If Not min >= max Then
' Pick a dividing value.
i = Int((max - min + 1) * Rnd + min)
midValue = newList(i)
' Swap the dividing value to the front.
newList(i) = newList(min)
low = min
high = max
Do
' Look down from hi for a value < mid_value.
Do While newList(high) >= midValue
high = high - 1
If high <= low Then Exit Do
Loop
If high <= low Then
newList(low) = midValue
Exit Do
End If
' Swap the lo and hi values.
newList(low) = newList(high)
' Look up from lo for a value >= mid_value.
low = low + 1
Do While newList(low) < midValue
low = low + 1
If low >= high Then Exit Do
Loop
If low >= high Then
low = high
newList(high) = midValue
Exit Do
End If
' Swap the lo and hi values.
newList(high) = newList(low)
Loop
' Sort the two sublists.
newList = QuickSort(newList, min, low - 1)
newList = QuickSort(newList, low + 1, max)
End If
QuickSort = newList
End Function