排序二维数组

时间:2014-05-31 10:34:34

标签: c# .net arrays sorting

我需要按升序排序二维数组,我用C#编写这个代码来排序数组,但是它对数组中的每一行排序并不是所有的二维数组,如何对所有二维数组进行排序

        double[,] test_Descriptor = new double[3, 3];

        double tempr;

        test_Descriptor[0,0]=7;
        test_Descriptor[1, 0] = 7;
        test_Descriptor[2, 0] = 5;
        test_Descriptor[0, 1] = 3;
        test_Descriptor[1, 1] = 0;
        test_Descriptor[2, 1] = 2;
        test_Descriptor[0, 2] = 1;
        test_Descriptor[1, 2] = 9;
        test_Descriptor[2, 2] = 1;


        for (int i = 0; i < test_Descriptor.GetLength(0); i++) // Array Sorting
        {
            for (int j = test_Descriptor.GetLength(1) - 1; j > 0; j--)
            {

                for (int k = 0; k < j; k++)
                {
                    if (test_Descriptor[i, k] > test_Descriptor[i, k + 1])
                    {
                        tempr = test_Descriptor[i, k];
                        test_Descriptor[i, k] = test_Descriptor[i, k + 1];
                        test_Descriptor[i, k + 1] = tempr;
                    }
                }
            }

        }

        for (int y = 0; y < 3; y++)
            for (int x = 0; x < 3; x++)
                Console.WriteLine("y={0}", test_Descriptor[x,y]);

     } 

2 个答案:

答案 0 :(得分:1)

对真正的2D数组进行排序很困难,因为排序算法必须考虑数组的2D结构。如果你

,你会更好
  • 制作一个大小为tmp[M*N]的简单数组,
  • 将数据复制到tmp
  • 排序tmp
  • 将已排序的数据复制回原始数组

以下是如何做到这一点:

double tmp[test_Descriptor.GetLength(0)*test_Descriptor.GetLength(1)];
for (int i = 0; i != test_Descriptor.GetLength(0); i++) {
    for (int j = 0; j != test_Descriptor.GetLength(1); j++) {
        tmp[i*test_Descriptor.GetLength(1)+j] = test_Descriptor[i, j];
    }
}
Array.sort(tmp);
for (int i = 0; i != test_Descriptor.GetLength(0); i++) {
    for (int j = 0; j != test_Descriptor.GetLength(1); j++) {
        test_Descriptor[i, j] = tmp[i*test_Descriptor.GetLength(1)+j];
    }
}

答案 1 :(得分:0)

相关问题