Recipe 8.2. Sorting Array Elements


Problem

You want to sort the elements of an array.

Solution

Sample code folder: Chapter 08\SortingArrays

Use the Sort() method of the Array class.

Discussion

The Array class has a shared Sort() method that works on arrays of any kind. There are several optional parameters that let you customize the sorting algorithm for different types of objects, but for arrays of strings and numbers, the name of the array is generally all you need to pass. The following example creates a string array containing the names of a few types of fruit, then sorts them into alphabetical order and displays the sorted list of fruit names for review:

 Dim result As New System.Text.StringBuilder Dim arrayToSort( ) As String = { _    "Oranges", "Apples", "Grapes", "Bananas", "Blueberries"} ' ----- Show the elements before sorting. result.AppendLine("Before sorting:") For Each fruit As String In arrayToSort    result.AppendLine(fruit) Next fruit ' ----- Show the elements after sorting. result.AppendLine( ) result.AppendLine("After sorting:") Array.Sort(arrayToSort) For Each fruit As String In arrayToSort    result.AppendLine(fruit) Next fruit MsgBox(result.ToString( )) 

The StringBuilder is first filled with the names of the fruits in the unsorted order used to create the string array. The Array.Sort() method is invoked to sort the fruits alphabetically, and the sorted fruits are then added to the StringBuilder to demonstrate the sorted order. Figure 8-1 shows the array before and after the sort.

Figure 8-1. Sorting arrays using the shared Sort( ) method of the Array class


Sorting intrinsic types is simple, but you can also sort custom classes based on any comparison criteria you specify. You do this by implementing the IComparable interface on the custom class. The following class implements a simple comparison interface that merges group and item values into a single string for comparison:

 Private Class CustomData    Implements IComparable    Public GroupName As String    Public ItemName As String    Public Sub New(ByVal theGroup As String, _          ByVal theItem As String)       GroupName = theGroup       ItemName = theItem    End Sub    Public Overrides Function ToString( ) As String       Return GroupName & ": " & ItemName    End Function    Public Function   CompareTo(ByVal obj As Object) As Integer _          Implements System.IComparable.CompareTo       ' ----- Compare two records.       Dim compareValue As String       ' ----- Since we're just going to compare the ToString       '       value, no need to convert to CustomData.       compareValue = obj.ToString( )       ' ----- Return the relative comparison value.       Return String.Compare(Me.ToString( ), compareValue)    End Function End Class 

The CompareTo() method returns a negative value if the object itself should come before another object supplied for comparison, a positive value if the instance should come after, and zero if they are equal. The String object's comparer was deferred to here, but you can use any complex calculations for comparison.

The following sample sorts an array of CustomData data elements:

 Dim result As New System.Text.StringBuilder Dim   arrayToSort( ) As CustomData = { _    New CustomData("Fruit", "Orange"), _    New CustomData("Vegetable", "Onion"), _    New CustomData("Fruit", "Apple"), _    New CustomData("Vegetable", "Carrot"), _    New CustomData("Fruit", "Grape")} ' ----- Show the elements before sorting. result.AppendLine("Before sorting:") For Each food As CustomData In arrayToSort    result.AppendLine(food.ToString( )) Next food ' ----- Show the elements after   sorting. result.AppendLine( ) result.AppendLine("After sorting:") Array.  Sort(arrayToSort) For Each food As CustomData In arrayToSort    result.AppendLine(food.ToString( )) Next food MsgBox(result.ToString( )) 

Figure 8-2 shows the output from this code.

Figure 8-2. Sorting custom data using the IComparable interface


See Also

Recipe 8.3 shows how to reverse the elements of an array, and Recipe 8.5 shows how to randomly rearrange the elements of an array.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net