gpt4 book ai didi

c# - 合并排序的 IndexOutOfRangeException

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:46 25 4
gpt4 key购买 nike

<分区>

我的类(class)是这样设计的:

    class MergeSort
{
int[] mArray;
public MergeSort(int[] A)
{
mArray = A;
}
void Merge(int[] A,int p ,int q, int r)
{
int n1 = q - p + r;
int i = 0, j = 0;
int n2 = r - q;
int[] left = new int[n1+1];
int[] right = new int[n2+1];
for ( i = 0; i < n1; i++)
left[i] = A[p + i - 1];
for ( i = 0; i < n2; i++)
right[i] = A[q + i];
left[n1] = Int32.MaxValue;
right[n2] = Int32.MaxValue;
i = j = 0;
for (int k = p; k < r; k++)
{
if (left[i] <= right[j])
{
A[k] = left[i];
i++;
}
else
{
A[k] = right[j];
j++;
}
}

}
public void Merge_Sort(int[] A, int p, int r)
{
int q = 0;
mArray = A;
if(p<r)
{
q = (p+r)/2;
Merge_Sort(A,p,q);
Merge_Sort(A, q + 1, r);
Merge(A,p,q,r);
}
}
public string show()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mArray.Length; i++)
{
sb.Append(mArray[i].ToString() + " ");
}
return sb.ToString();
}
}

这就是我进行排序的方式:

        int[] arr = { 10, 12, 5, 6, 30, 1, 11, 120, 12 };
MergeSort ms = new MergeSort(arr);
ms.Merge_Sort(arr, 0, arr.Length );
MessageBox.Show(ms.show());

但我在 Merge 函数的许多地方不断收到错误 Index was outside the bounds of the array.。我已经尝试按照 CLRS(Coremen)的书中所述实现算法。但是我一直收到这个错误,我已经处理了 3 天了 - 请帮忙。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com