QuickSort (2)



Sub Quicksort (List() As Long, min As Integer, max As Integer)
Dim med_value As Long
Dim hi As Integer
Dim lo As Integer
Dim i As Integer
' If the list has no more than 1 element, it's sorted.

If min >= max Then Exit Sub
' Pick a dividing item.

i = Int((max - min + 1) * Rnd + min)
med_value = List(i)
' Swap it to the front so we can find it easily.

List(i) = List(min)
' Move the items smaller than this into the left

' half of the list. Move the others into the right.

lo = min
hi = max
Do
' Look down from hi for a value < med_value.

Do While List(hi) >= med_value
hi = hi - 1
If hi <= lo Then Exit Do
Loop
If hi <= lo Then
List(lo) = med_value
Exit Do
End If
' Swap the lo and hi values.

List(lo) = List(hi)

' Look up from lo for a value >= med_value.

lo = lo + 1
Do While List(lo) < med_value
lo = lo + 1
If lo >= hi Then Exit Do
Loop
If lo >= hi Then
lo = hi
List(hi) = med_value
Exit Do
End If
' Swap the lo and hi values.

List(hi) = List(lo)
Loop
' Sort the two sublists

Quicksort List(), min, lo - 1
Quicksort List(), lo + 1, max
End Sub

(quicksort2.html)- by Paolo Puglisi - Modifica del 25/3/2019