我已经阅读了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++;
}
}
}
答案 0 :(得分:0)
修复了以下注释中指出的问题。将数据从输入移动到valStanga的第一个解决方案。合并回输入的范围的第二个解决方法。合并参数的顺序是异常,第一,最后,中间。通常顺序是第一,中间,最后。
注释:如果要排序的数组包含等于最大整数的元素,则程序将出现问题。一次性分配一个工作数组比在每次合并调用中分配新的子数组要高效。通过更改每个递归级别的合并方向可以避免复制操作。
{
"type": "array",
"items": {
"type": "object",
"properties": {
"prop": {
"type": "object",
"properties": {
"name": {
"prop1": "string"
},
"type": {
"prop2": "string"
},
"amount": {
"prop3": "number"
},
"operation": {
"prop4": "string"
}
},
"oneOf": [
{ "required": ["prop1", "prop2", "prop3", "prop4"] },
{ "required": [] }
]
}
}
}
}