Sort Arrays By Your Rules

There are several algorithms to sort arrays of data, each following a different set of steps and each requiring a different amount of space and time. At some point, though, all algorithms need to perform a basic comparison between two elements in the sortable array. Most libraries provide a hard-coded sort algorithm (usually, the QuickSort algorithm) and just a hook for you to provide some external code to compare objects. All sort algorithms, in fact, just need to know for each pair of objects which is greater, no matter how you determine this. On the other hand, determining the greater of two objects is a strictly application-specific task.


In the .NET Framework, you sort array using the Sort method on the Array class, as shown below.




The method sorts the entire array using the default comparer to determine if one object is greater than the next.  The Sort method uses the QuickSort algorithm internally. It is important to note that all objects in the array must implement the IComparable interface in order to be comparable to all other elements in the array. This is not an issue if you use basic types; bear it in mind if you happen to sort arrays of custom objects.


Whats a comparer? A comparer is a class that implements the IComparer interface. The interface exposes a method that compares two objects. Native comparers available in the .NET Framework are Comparer and CaseInsensitiveComparer classes. The former compare strings in case-sensitive way; the latter does the reverse. Heres the code needed to sort an array in a case-insensitive way:


Array.Sort(myArr, CaseInsensitiveComparer.Default)


What if you want to use your own rules to sort the elements of an array? In this case, you just write your own comparer class and pass an instance of it to the Sort method.


Public Class MyComparer : Implements IComparer

 Function Compare(x As Object, y As Object) As Integer _

    Implements IComparer.Compare

   Dim numX As Integer = CType(x, Integer)

   Dim numY As Integer = CType(y, Integer)


   Dim isEvenX As Integer = (numX Mod 2)

   Dim isEvenY As Integer = (numY Mod 2)


   If isEvenX = isEvenY Then

      Return numX.CompareTo(numY)

   End If


   Return isEvenX.CompareTo(isEvenY)

 End Function

End Class


The code shows how to sort numbers in such as way even numbers come first ordered from lowest to greatest. To use this class do as follows:


Array.Sort(Numbers, New MyComparer)

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.