c# 2D array 冒泡排序

c# 2D array bubblesort

我正在尝试对二维数组执行冒泡排序,按第三个索引(整数)排序​​

string[,] edges = new string[,] { {"A", "B", "2"},
                                          {"A", "C", "3"},
                                          {"A", "E", "10"},
                                          {"B", "C", "5"},
                                          {"B", "D", "10"},
                                          {"C", "D", "2"},
                                          {"D", "E", "5"},
                                          {"E", "B", "3"}
                                        }; 

我在排序代码的 IF 语句中得到一个 IndexOutOfRangeException

        string[] temp = {};

        //sort edges and add them to sortedEdges - using bubblesort
        for (int i = 0; i < edges.Length - 1; i++){
            for (int j = 0; j < edges.Length - 1; j++){
                if (Int32.Parse(edges[i, 2]) > Int32.Parse(edges[i + 1, 2])){
                    //make a swap
                    //put array record i into temp holder
                    temp[0] = edges[i, 0];
                    temp[1] = edges[i, 1];
                    temp[2] = edges[i, 2];

                    //copy i + 1 into i
                    edges[i, 0] = edges[i + 1, 0];
                    edges[i, 1] = edges[i + 1, 1];
                    edges[i, 2] = edges[i + 1, 2];

                    //copy temp into i + 1
                    edges[i + 1, 0] = temp[0];
                    edges[i + 1, 1] = temp[1];
                    edges[i + 1, 2] = temp[2];

                }
            }
        }

我的问题是,我该如何解决这个问题,以便数组 "edges" 中充满按第三列排序的行?

谢谢。

已更新 v-3

对于这样定义的 table,问题出在 Length 中,在您的情况下是 24,因为它似乎计算了两个维度中的所有元素。 请尝试以下代码:

string[] temp = new string[3];

for (int i = 0; i < edges.GetLength(0) - 1; i++){
    int j;
    j = 0;
    for (; j < edges.GetLength(0) - 1; j++){

        if (Int32.Parse(edges[j, 2]) > Int32.Parse(edges[j + 1, 2])){
            //make a swap
            //put array record j into temp holder
            temp[0] = edges[j, 0];
            temp[1] = edges[j, 1];
            temp[2] = edges[j, 2];

            //copy j + 1 into j
            edges[j, 0] = edges[j + 1, 0];
            edges[j, 1] = edges[j + 1, 1];
            edges[j, 2] = edges[j + 1, 2];

            //copy temp into j + 1
            edges[j + 1, 0] = temp[0];
            edges[j + 1, 1] = temp[1];
            edges[j + 1, 2] = temp[2];

        }
    }
}

您可以在此处找到(更新的)工作示例:https://dotnetfiddle.net/FQs4OA