Sorting a jagged array

by david 4. December 2009 17:30

This week, I had a need to sort a jagged array of integers, and this is the solution that I came up with:

 

public class IntArraySorter

{

    public static void ExampleSorting()

    {

        int[] a = new int[5] { 1,2,3,4,0 };

        int[] b = new int[4] { 1,2,3,0 };

        int[] c = new int[3] { 1,2,0 };

        int[] d = new int[2] { 1,0 };

        int[] e = new int[1] { 1 };

 

        // sort a 2 dimensional array of integers

        int[][] multi = new int[5][] {a,b,c,d,e};

        Array.Sort(multi, CompareIntArrays);

 

        // we can also use it to sort a List of integer arrays

        List<int[]> list = new List<int[]>();

        list.AddRange(new int[][] {a,b,c,d,e });

        list.Sort(CompareIntArrays);

        int your_breakpoint_here = 0;

    }

 

    public static int CompareIntArrays(int[] x, int[] y)

    {

        int length = x.Length > y.Length ? x.Length : y.Length;

        int diff = 0;

        for (int t = 0; t < length; t++)

        {

            diff = safeGet(x, t) - safeGet(y, t);

            if (diff != 0) return diff;

        }

        return x.Length - y.Length;

    }

    private static int safeGet(int[] arr, int element)

    {

        return (element > arr.Length - 1) ? 0 : arr[element];

    }

}

 

...this technique will work with 2 dimensional arrays of integers if they are jagged or not.  So I thought that it was the type of thing that was worth posting up here for future reference.

About the author

David

I'm a C# developer having worked with .Net since it was in beta.  Before that I mainly worked in C and C++.  I have been developing commercial software for more than 20 years.  I also mess around with microprocesors, but that's just for fun.  I live near Cambridge, England and at the moment I'm contracted to one of the departments at Cambridge University.

Related Links

Tag cloud