我正在尝试在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];
}
}
}
我的问题是,如何解决这个问题,以便数组“edge”填充行,按第三列排序?
感谢。
答案 0 :(得分:0)
更新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