#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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: