简体   繁体   English

使用插入排序C#按第二列对锯齿状数组进行排序

[英]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: 我在ac#程序中声明了一个锯齿状数组,其中第一列代表一年,第二列代表一个月数(1-12),第三列代表该月的一些数据:

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# 它必须是自定义算法,不能使用C#附带的Array.Sort算法。

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: 其中Algorithms.Swap是另一个小帮手:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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