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数组。
exception(index out of bound when I call from main() method using Merge(arr,0,0,12)
在这一部分,您将获得一个索引超出范围的异常:
for (int i = 0; i < n2; i++) R[i] = arr[q+i];
您的R数组的大小为0,而使用给定参数将n2定义为12。