【问题标题】:Sort jagged array by second column using insertion sort C#使用插入排序 C# 按第二列对锯齿状数组进行排序
【发布时间】:2016-08-08 21:49:35
【问题描述】:

我在一个 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},
        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 算法

谢谢

【问题讨论】:

  • 不,这是我需要学习的任务的一部分,但没有笔记

标签: c# algorithm sorting insertion-sort jagged-arrays


【解决方案1】:

通过定义两个函数,插入排序算法可以很容易地推广(抽象)以处理索引——一个比较两个索引,一个交换两个索引,如下所示:

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; }

【讨论】:

  • 我假设,为了反转这个,我只是在第二个 for 循环中交换大于号?
  • 如果你的意思是降序排序,你可以这样做,但最好保持算法干净(原样),并反转调用者的compare Func,例如data[1][b].CompareTo(data[1][a])
猜你喜欢
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 2020-12-31
  • 2023-01-10
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多