Sorting Arrays


If you have a list of names , you would most likely want to present it sorted alphabetically to the client. Or you may want to use a faster mechanism for searching through the items of the array, called a binary search. For the binary search to work properly, the items in the array need to be sorted.

To sort the elements of an array:

  1. Type System.Array.Sort .

  2. Type an open parenthesis ( .

  3. Type the name of the variable that points to the array you wish to sort: names , for example.

  4. Type a close parenthesis ) .

  5. Type a semicolon ; ( Figure 9.39 ).

    Figure 9.39 It's really easy to sort an array with the Array.Sort function. All you do is pass in a single dimensional array and the elements will be sorted.
     void Task() {    string[] names = new string[]    {"James","Bill","Angel","Sally"};  Array.Sort(names);  foreach(string name in names)    {       Response.Write(name + ",");  //prints Angel, Bill, James, Sally,  } } 

graphics/tick.gif Tips

  • Sorting only works with one-dimensional arrays.

  • String sorting is case sensitive by default. However, you can ask it to make caseinsensitive comparisons using one of the versions of the Sort function that accepts the IComparer interface and passing the CaseInsensitiveComparer to it ( Figure 9.40 ).

    Figure 9.40 By default, string comparisons are case sensitive, but the .NET framework includes a comparer object that can perform case-insensitive comparisons.
     void Task() {    string[] names = new string[]    {"A","a","A","A","a","a"};    Array.Sort(names);    foreach(string name in names)    {       Response.Write(name + ",");       //prints a,a,a,A,A,A    }    Response.Write("<br>");    Array.Sort(names,  System.Collections.   CaseInsensitiveComparer.Default  );    foreach(string name in names)    {       Response.Write(name + ",");       //prints A,A,A,a,a,a    } } 
  • There is no version of Sort that enables you to sort the array in descending order, but that's not hard to do if you write your own comparer object. The Sort function basically tells whatever comparer object you give it to compare two items. The comparer object then returns -1 if the first item is less than the second, 1 if it is greater, and 0 if they are equal. The .NET Framework already has a class called Comparer that does this for strings, but in ascending order. All we have to do is create a class that in its compare method returns the opposite of the Comparer class. See Figure 9.41 for details.

    Figure 9.41 A comparer is a class that performs comparisons. It needs to implement the IComparer interface which has a single method called Compare. In this case we return the opposite of the default comparer so that our items end up in reverse order.
     class Reverse : System.Collections.IComparer {  public int Compare(object x, object y)   {   int result = System.Collections.   Comparer.Default.Compare(x,y);   return -1 * result; //return the   opposite   }  } void Task() {    string[] names = new string[]    {"Anna","Bill","Charles"};    Array.Sort(names,  new Reverse()  );    foreach(string name in names)    {       Response.Write(name + ",");       //prints Charles,Bill,Anna,    } } 
  • In the last section we talked about searching for items in an array of custom classes and I pointed out that searching for a custom class involved overriding the Equals method of your class. Sorting an array of a custom class also requires extra work. This is because it is impossible for the framework to know how to sort two instances of a custom class without your help. For that reason the .NET framework has an interface called IComparable that you can implement in your class to help the sort function. The IComparable interface has a single method: Compare . In this method you are given an instance of another object and asked to compare yourself to it. If you are less than the item, you return -1. If you are greater, you return 1. If you are equal, you return 0. It's up to you to determine if you are less than, greater than, or equal, based on the information in the fields of the class. For example, a class called Person may have a field called Age and you may want to sort based on the Age field. In that case you would compare the Age field of both elements and return either -1, 0, or 1 ( Figure 9.42 ).

    Figure 9.42 Implementing IComparable is necessary if you want to sort an array of custom objects. It has a single method called CompareTo.
     class Person : IComparable {    public string Name;    public int Age;    public Person(string name, int age)    {       Name = name;       Age = age;    }  public int CompareTo(object obj)  {       if (obj is Person)       {          Person temp = (Person)obj;          return Age.CompareTo(temp.Age);       }       throw new ArgumentException       ("Not a person","obj");    } } void Task() {    Person[] friends = new Person[]    { new Person("Bill",28),      new Person("Jim",31),      new Person("Jason",29) };    Array.Sort(friends);    //returns Bill,Jason,Jim } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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