Array of Objects Sorting Using Bubble Sort

This demo illustrates how to perform a sort on an array of objects using Bubble Sort.

Unsorted List of Array of Objects:
Paul - Male - 31
Darren - Male - 32
Anne - Female - 30

Sorted List of an Array of Objects:
Anne - Female - 30
Darren - Male - 32
Paul - Male - 31

Souce Code:
 ```<% Sub ObjSorter( byRef arrArray ) Dim row, k Dim objStartingKey, objSmallestKey Dim ValueToCompare Dim swap_pos For row = 0 To UBound( arrArray ) - 1 'Start OUTER loop. 'Take a snapshot of the first element 'in the array because if there is a 'smaller value elsewhere in the array 'we'll need to do a swap. Set objStartingKey = arrArray (row) Set objSmallestKey = arrArray (row) swap_pos = row For k = row + 1 to UBound( arrArray ) ' Start INNER loop. ' Call the objects Compare method of the current ' objSmallestKey object. Pass in the object that we are ' comparing against. ValueToCompare = objSmallestKey.Compare( arrArray(k) ) ' If 1 was returned then the value in arrArray(k) ' was smaller, so we do a swap. If ValueToCompare = 1 Then ' This is now the lowest number - ' remember it's position. swap_pos = k Set objSmallestKey = arrArray ( k ) End If Next If swap_pos <> row Then ' If we get here then we are about to do a swap ' within the array. Set arrArray ( swap_pos ) = objStartingKey Set arrArray ( row ) = objSmallestKey End If Set objStartingKey = Nothing Set objSmallestKey = Nothing Next End Sub Class Person Public Name Public Age Public Sex Public Function Compare (objOther) ' Default Compare for the Class is to sort by Name Compare = strComp( me.Name, objOther.Name, vbTextCompare ) End Function End Class Dim aPerson, bPerson, cPerson Set aPerson = New Person aPerson.Name = "Paul" aPerson.Age = 31 aPerson.Sex = "Male" Set bPerson = New Person bPerson.Name = "Darren" bPerson.Age = 32 bPerson.Sex = "Male" Set cPerson = New Person cPerson.Name = "Anne" cPerson.Age = 30 cPerson.Sex = "Female" Dim arrArray, i arrArray = Array(aPerson, bPerson, cPerson) Response.Write "Unsorted List of Array of Objects:
" For i = LBound(arrArray) to UBound(arrArray) Response.Write arrArray(i).Name & " - " Response.Write arrArray(i).Sex & " - " Response.Write arrArray(i).Age & "
" Next call ObjSorter(arrArray) Response.Write "

Sorted List of an Array of Objects:
" For i = LBound(arrArray) to UBound(arrArray) Response.Write arrArray(i).Name & " - " Response.Write arrArray(i).Sex & " - " Response.Write arrArray(i).Age & "
" Next %> ```

[Back to the article] | [View the "sorting an two-dimensional array" demo]