#134 – Sorting One-Dimensional Arrays

You can sort a one-dimensional array of elements using the static Array.Sort method.  This requires that the underlying type of the array elements implements the IComparable interface.  Types that implement IComparable include: all built-in numeric types (e.g. int, float, double), char, string and DateTime types.

Here’s an example that sorts an array of integers:

 int[] nums = new int[5];
 nums[0] = 3; nums[1] = 2; nums[2] = 4;
 nums[3] = 1; nums[4] = 0;

 Array.Sort(nums);   // Elements now: 0, 1, 2, 3, 4

Here’s an example of sorting an array of strings:

 string[] emps = new string[4];
 emps[0] = "Augustus";
 emps[1] = "Tiberius";
 emps[2] = "Caligula";
 emps[3] = "Claudius";
 Array.Sort(emps);   // Augustus, Caligula, Claudius, Tiberius

You can’t sort an array of objects, if the element type does not implement IComparable:

 Cat[] cats = new Cat[2];
 cats[0] = new Cat("Garfield", "Sleep all day");
 cats[1] = new Cat("Buster", "Scratch everything");
 Array.Sort(cats);    // throws InvalidOperationException

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment