【发布时间】:2019-07-13 19:18:37
【问题描述】:
我已阅读 CLRS 并尝试实现递归合并排序算法。看不到错误是什么,但每次我运行它都会给我一个“索引超出范围错误”
我已经尝试了 5 个小时了
static public void MergeSort(int[] input, int IndexStanga, int IndexDreapta)
{
if (IndexStanga < IndexDreapta)
{
int IndexMijloc = (IndexDreapta + IndexStanga) / 2;
MergeSort(input, IndexStanga, IndexMijloc);
MergeSort(input, IndexMijloc + 1, IndexDreapta);
Merge(input, IndexStanga, IndexDreapta, IndexMijloc);
}
}
static public void Merge(int[] input, int stanga, int dreapta, int mijloc)
{
int lungDR = 0;
int lunST = 0;
lungDR = dreapta - mijloc;
lunST = mijloc - stanga + 1;
int[] valDreapta = new int[lungDR + 1];
int[] valStanga = new int[lunST + 1];
valDreapta[valDreapta.Length - 1] = int.MaxValue;
valStanga[valStanga.Length - 1] = int.MaxValue;
int i = 0;
int j = 0;
for (i = stanga; i <= mijloc; i++) valStanga[i] = input[i];
for (i = 0; i < lungDR; i++) { valDreapta[i] = input[i + mijloc + 1]; }
i = 0;
j = 0;
for (int k = 0; k < input.Length; k++)
{
if (valStanga[i] <= valDreapta[j]) //error out of bounds
{
input[k] = valStanga[i];
i++;
}
else
{
input[k] = valDreapta[j];
j++;
}
}
}
【问题讨论】:
-
作为对 Stack Overflow 上所有非罗马尼亚开发人员的服务,您能否将参数等重命名为英文以使其更易于理解,从问题中删除一层抽象?跨度>
-
知道错误的行号也很好......虽然我怀疑它是使用
i和j索引但未在条件语句中使用的地方for 循环。 -
使用调试器。它会准确告诉您错误发生的位置,您可以检查所有值是否正确。
-
对不起,我匆忙发布了这个问题,老实说,我没想到会有任何答案......无论如何,伙计们!
-
错误位于“ for (int k = 0; k