VB.NET - Code Samples - Sort Custom Class Collection

VB.NET Sort Collection Algorithm

Synopsis:

This function performs a simple BubbleSort on any property of the class contained within a collection

The Reason:

I had the need to sort a collection of objects on different properties at different times. The items were usually almost near sort order so a Bubblesort was a logical choice.

The Code:

 'performs a bubblesort on an object collection for the specified property
    Public Sub SortObjectCol(ByVal List As ArrayList, ByVal min As Integer, _
        ByVal max As Integer, ByVal propName As String)
        Dim last_swap As Integer
        Dim i As Integer
        Dim j As Integer
        Dim tmp As Object

        ' Repeat until we are done.
        Do While min < max
            ' Bubble up.
            last_swap = min - 1
            ' For i = min + 1 To max
            i = min + 1
            Do While i <= max
                ' Find a bubble.
                If CallByName(List(i - 1), propName, CallType.Get) > CallByName(List(i), propName, CallType.Get) Then
                    ' See where to drop the bubble.
                    tmp = List(i - 1)
                    j = i
                    Do
                        List(j - 1) = List(j)
                        j = j + 1
                        If j > max Then Exit Do
                    Loop While CallByName(List(j), propName, CallType.Get) < CallByName(tmp, propName, CallType.Get)
                    List(j - 1) = tmp
                    last_swap = j - 1
                    i = j + 1
                Else
                    i = i + 1
                End If
            Loop
            ' Update max.
            max = last_swap - 1

            ' Bubble down.
            last_swap = max + 1
            ' For i = max - 1 To min Step -1
            i = max - 1
            Do While i >= min
                ' Find a bubble.
                If CallByName(List(i + 1), propName, CallType.Get) < CallByName(List(i), propName, CallType.Get) Then
                    ' See where to drop the bubble.
                    tmp = List(i + 1)
                    j = i
                    Do
                        List(j + 1) = List(j)
                        j = j - 1
                        If j < min Then Exit Do
                    Loop While CallByName(List(j), propName, CallType.Get) > CallByName(tmp, propName, CallType.Get)
                    List(j + 1) = tmp
                    last_swap = j + 1
                    i = j - 1
                Else
                    i = i - 1
                End If
            Loop
            ' Update min.
            min = last_swap + 1
        Loop
    End Sub


    'sample use syntax
    'SortObjectCol(col, 0, col.Count - 1, "ID")
About this page: