public static void Merge(int[] arr,int p,int q,int r )
{
int n1 = q-p;
int n2 = r-q;
int[] L=new int[n1];
int[] R = new int[r-n2];
for (int i = 0; i < n1; i++)
L[i] = arr[i];
foreach (int x in L)
Console.WriteLine(x);
for (int i = 0; i < n2; i++)
R[i] = arr[q+i];
Console.WriteLine("New part");
foreach (int x in R)
Console.WriteLine(x);
int k=0, d=0;
for (int i = p; i < r; i++)
{
if (L[k] <= R[k])
{
arr[i] = L[k];
k++;
}
else
{
arr[i] = R[d];
d++;
}
}
}
以上代码显示exception(index out of bound when I call from main() method using Merge(arr,0,0,12)
。其中arr是长度为12的int数组。
答案 0 :(得分:2)
这部分你得到一个索引越界异常:
for (int i = 0; i < n2; i++)
R[i] = arr[q+i];
你的R数组大小为0,而n2定义为12,给定的参数。
答案 1 :(得分:1)
数组L的大小为q-p,均为0
答案 2 :(得分:1)
L和R数组都定义为太小
将其初始化为:
int[] L = new int[arr.Length];
int[] R = new int[arr.Length];