[英]Sort jagged array by second column using insertion sort C#
我在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}
};
如您所見,第一個數組是有序的。 我想知道如何按這樣的升序按第二列對鋸齒狀數組進行排序。
{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#附帶的Array.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]); });
其中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.