10
Apr
09

[Vb.Net] QuickSort

This uses the QuickSort algorithm to order a list of numbers:

  Private Function QuickSort(ByVal ListOfNumbers As List(Of Integer)) As List(Of Integer)
        ''If the list is 1 or 0 then it is sorted
        If ListOfNumbers.Count < 1 Then Return ListOfNumbers
        ''List of numbers smaller than the pivot, and larger than it
        Dim SmallList, LargeList As New List(Of Integer)
        ''Pivot = n/2 rounded down
        Dim Pivot As Integer = ListOfNumbers(Math.Floor((ListOfNumbers.Count) / 2))
        Dim PivotCount As Integer = 0
        QuickSort = New List(Of Integer)
        ''Add to appropriate list
        For i As Integer = 0 To ListOfNumbers.Count - 1
            If ListOfNumbers(i) < Pivot Then
                SmallList.Add(ListOfNumbers(i))
            ElseIf ListOfNumbers(i) > Pivot Then
                LargeList.Add(ListOfNumbers(i))
            Else
                PivotCount = PivotCount + 1
            End If
        Next
        ''Quicksort smaller list
        QuickSort.AddRange(QuickSort(SmallList))
        ''Add pivot
        While PivotCount > 0
            QuickSort.Add(Pivot)
            PivotCount -= 1
        End While
        ''Sort large list 
        QuickSort.AddRange(QuickSort(LargeList))
    End Function

Usage:

        Dim ArrayOfNumbers As Integer() = {21, 18, 16, 20, 11, 17, 15, 7, 3, 18, 19, 14, 11, 28, 12, 15, 7, 30, 27}
        Dim ListOfNumbers As New List(Of Integer)
        ListOfNumbers.AddRange(ArrayOfNumbers)
        For Each Number As Integer In QuickSort(ListOfNumbers)
            Debug.Write(Number & " ")
        Next
        Debug.Write(vbNewLine)

Would Output:
3 7 7 11 11 12 14 15 15 16 17 18 18 19 20 21 27 28 30

Advertisements

0 Responses to “[Vb.Net] QuickSort”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: