Quick Sort

Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.
The steps are:
1) Pick an element, called a pivot, from the list.
2) Reorder the list so that all elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3) Recursively sort the sub-list of lesser elements and the sub-list of greater elements.
The base case of the recursion are lists of size zero or one, which are always sorted. The algorithm always terminates because it puts at least one element in its final place on each iteration (the loop invariant).

Sub Quicksort(values(), ByVal min As Long, ByVal max As Long) 

  Dim med_value As String
  Dim hi As Long
  Dim lo As Long
  Dim i As Long

' If the list has only 1 item, it's sorted.
  If min >= max Then Exit Sub

' Pick a dividing item randomly.
  i = min + Int(Rnd(max - min + 1))
  med_value = values(i)

' Swap the dividing item to the front of the list.
  values(i) = values(min)

' Separate the list into sublists.
  lo = min
  hi = max
' Look down from hi for a value < med_value.
    Do While values(hi) >= med_value
      hi = hi - 1
      If hi <= lo Then Exit Do

    If hi <= lo Then
' The list is separated.
      values(lo) = med_value
      Exit Do
    End If

' Swap the lo and hi values.
    values(lo) = values(hi)

' Look up from lo for a value >= med_value.
    lo = lo + 1
    Do While values(lo) < med_value
      lo = lo + 1
      If lo >= hi Then Exit Do

    If lo >= hi Then
' The list is separated.
      lo = hi
      values(hi) = med_value
      Exit Do
    End If

' Swap the lo and hi values.
    values(hi) = values(lo)
  Loop ' Loop until the list is separated.

' Recursively sort the sublists.
  Quicksort values, min, lo - 1
  Quicksort values, lo + 1, max

End Sub

© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext