c# 二维数组气泡排序

本文关键字:排序 气泡 二维数组 | 更新日期: 2023-09-27 18:36:00

我正在尝试对 2D 数组执行气泡排序,按第三个索引(整数)排序

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

我的问题是,我如何解决这个问题,以便数组"边缘"填充按第三列排序的行?

谢谢。

c# 二维数组气泡排序

更新 v-3

问题出在这种定义的表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