Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleSort a list using quicksort
Keywordssorting, quicksort, algorithms
CategoriesAlgorithms
 
See the book Ready-to-Run Visual Basic Algorithms for more information on this and other sorting algorithms.

Note that quicksort works very well with lists that are initially randomly arranged and that do not contain too many duplicate values. Under other circumstances, see the book for better sorting algorithms.

 
Public Sub Quicksort(list() As Integer, ByVal min As Long, _
    ByVal max As Long)
Dim med_value As Long
Dim hi As Long
Dim lo As Long
Dim i As Long

    ' If min >= max, the list contains 0 or 1 items so it
    ' is sorted.
    If min >= max Then Exit Sub

    ' Pick the dividing value.
    i = Int((max - min + 1) * Rnd + min)
    med_value = list(i)

    ' Swap it to the front.
    list(i) = list(min)

    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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated