Arrays Sortability and Searchability

If you take a look at the entire System.Array interface as documented in the MSDN documentation, you’ll notice that several methods have to do with sorting the items within the array. These methods are usable when the contained type implements IComparable, the standard interface through which items of a particular type are compared.3 Naturally, you cannot sort a multidimensional array, and if you try, you’ll need to be ready to catch an exception of type RankException. So, always be cognizant of what types of things could go wrong when you’re calling methods on arrays to do what could appear to be failproof operations.

Using the static methods Index and LastIndexOf, you can locate a specific value within an array. If the method fails to find the requested value, it returns -1. No particular search algorithm is involved with these methods other than the fact that the former starts searching from the beginning of the array and the latter starts at the end. If you’d like to perform a faster search, you can use the BinarySearch static method. However, before you can do so, you must sort your array, and of course, that requires that the items within the array implement IComparable/IComparable<T> or you must provide a type that implements IComparer/IComparer<T> which is passed to the Sort method.

The difference between whether your type implements IComparable/IComparable<T> or whether you provide another type which implements IComparer/IComparer<T> to perform the comparison of two instances is a subtle but important one. As Jon Skeet points out, separating the comparison logic from the type itself facilitates greater flexibility. Sort methods should provide an overload that accepts a type that implements IComparer/IComparer<T> which the Sort method then delegates to in order to compare two instances. This design whereby one can provide the algorithm at the time of the sort is a form of the Strategy pattern.

Source Of Information : Apress Accelerated C Sharp 2010


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner