C# 使用插入排序C按第二列对锯齿状数组排序#
我在c#程序中有一个锯齿状数组,其中第一列表示一年,第二列表示一个月的数字(1-12),第三列表示该月的一些数据:C# 使用插入排序C按第二列对锯齿状数组排序#,c#,algorithm,sorting,insertion-sort,jagged-arrays,C#,Algorithm,Sorting,Insertion Sort,Jagged Arrays,我在c#程序中有一个锯齿状数组,其中第一列表示一年,第二列表示一个月的数字(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},
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}
};
如您所见,第一个数组是有序的。我想知道如何按第二列按升序对锯齿状数组进行排序,如下所示
{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...
我的问题是,如何使用插入排序实现这一点。它需要是一个自定义算法,不能使用作为C语言一部分的数组.Sort算法#
多亏了插入排序算法可以通过定义两个函数(一个用于比较两个索引,另一个用于交换两个索引)轻松地推广(抽象)到索引上,如下所示:
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);
}
}
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]); });
其中算法.Swap
是另一个小助手:
public static void Swap<T>(ref T a, ref T b) { T c = a; a = b; b = c; }
publicstaticvoidswap(refta,reftb){tc=a;a=b;b=c;}
不,这是我需要学习的任务的一部分,但我没有任何笔记,要想颠倒这个,我只需将第二个循环中的大于号符号替换为循环?如果你想按降序排序,你可以这样做,但最好保持算法干净(原样),并反转调用方的比较函数,例如数据[1][b]。比较(数据[1][a])