合并排序code不工作并显示异常异常、工作、code

2023-09-11 02:21:01 作者:最好听的6个字的名字

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++;
        }
    }
}

以上code显示异常(索引出界的时候,我从main()方法使用合并(ARR,0,0,12)在哪里打电话ARR是一个长度为12的int数组。

The above code shows exception(index out of bound when I call from main() method using Merge(arr,0,0,12). Where arr is an int array of length 12.

推荐答案

您在这个环节得到一个索引越界异常:

You get an Index out of bounds exception in this part:

for (int i = 0; i < n2; i++)
R[i] = arr[q+i];

您R-数组大小为0,而N2被定义为12与给定的参数。

Your R-array is of size 0, while n2 is defined as 12 with the given arguments.