简体   繁体   中英

Sort jagged array by second column using insertion sort C#

I have a jagged array in ac# program that is declared where column one represents a year, column two represents the number of a month (1-12) and column three represents some data for that month:

double[][] data = new double[3][]
    {
        new double[] {1930,1931,1931,1931,1931,1931,1931,1931,1931,1931,1931,1931,1931,1932,1932,1932,1932,1932,1932,1932,1932,1932,1932,1932,1932},
        new double[] {12,  1,   2,   3,   4,   5,   6,   7,   8,   9,   10,  11,  12,  1,   2,   3,   4,   5,   6,   7,   8,   9,   10,  11,  12},
        new double[] {5,   6,   8,   3,   5,   8,   9,   6,   5,   6,   7,   5,   3,   2,   2,   2,   5,   7,   8,   3,   2,   2,   1,   2,   5}
    };

As you can see, the first array is ordered. I would like to know how I could sort the jagged array by the second column , in ascending order like this.

{1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1931,1932,1930,1931,1932}
{1,   1,   2,   2,   3,   3,   4,   4,   5,   5,   6,   6,   7,   7,   8,   8,   9,   9,   10,  10,  11,  11,  12,  12,  12}
etc...

My question is, how would I be able to implement this using an insertion sort. It needs to be a custom algorithm and cannot make use of the Array.Sort algorithm that comes as part of C#

Thanks

The insertion sort algorithm can easily be generalized (abstracted) to work on indexes by defining two functions - one to compare two indexes and one to swap two indexes, like this:

public static class Algorithms
{
    public static void InsertionSort(int start, int count, Func<int, int, int> compare, Action<int, int> swap)
    {
        for (int i = start + 1, end = start + count; i < end; i++)
            for (int j = i; j > start && compare(j - 1, j) > 0; j--)
                swap(j - 1, j);
    }
}

Now you can achieve your goal by comparing second columns and swap all columns like this:

Algorithms.InsertionSort(0, data[1].Length,
    (a, b) => data[1][a].CompareTo(data[1][b]),
    (a, b) => { foreach (var col in data) Algorithms.Swap(ref col[a], ref col[b]); });

where Algorithms.Swap is another little helper:

public static void Swap<T>(ref T a, ref T b) { T c = a; a = b; b = c; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM