Sorting Parallel Arrays Using C#

A very common coding design pattern is using parallel arrays. For example, suppose you have an array of people’s ages:

[21, 32, 32, 47, 51]

And a parallel arrays of the people’s hourly pay rates:

[16.00, 21.00, 19.00, 28.00, 17.00]

Now suppose you want to sort this data by payrate, from low to high. One approach is to use a neat overload of the Array.Sort function in C#:

int[] ages = 
  new int[] { 21, 32, 32, 47, 51 };
double[] payrates =
  new double[] { 16.00, 21.00, 19.00, 28.00, 17.00 };
Array.Sort(payrates, ages, payrates.Length);

This will sort the payrates but will also rearrange the ages in synch. The result is:

payrates = [16.00, 17.00, 19.00, 21.00, 28.00]
ages     = [ 21,    51,    32,    32,    47  ]   

Very nice little coding trick.

An alternative C# approach is to create a class structure that inherits from the IComparable interface along the lines of:

public class AgeAndRate : IComparable(AgeAndRate)
{
  public int age;
  public double rate;

  public int CompareTo(IndexAndDistance other) {
    if (this.dist lt other.dist) return -1;
    else if (this.dist gt other.dist) return +1;
    else return 0;  }
}

. . . 

Array.Sort(arrayOfAgeRateObjects);

In many situations the parallel arrays sorting trick is simpler and better.



I have always loved magic. The magician’s assistant is an important part of stage shows. There aren’t many movies that feature magicians but well-known actresses Scarlett Johansson (“The Prestige”, 2006) and Olivia Wilde (“The Incredible Burt Wonderstone”, 2013) have played the assistant’s role.

This entry was posted in Miscellaneous. Bookmark the permalink.

1 Response to Sorting Parallel Arrays Using C#

  1. Yeah i like tricks, but argh, i dont get it.

Comments are closed.