具有合并排序的IndexOutOfRangeException

时间:2013-11-03 16:32:28

标签: c# algorithm c#-4.0 sorting mergesort

这就是我的班级设计方式:

    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());

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

1 个答案:

答案 0 :(得分:1)

您在行left[i] = A[p + i - 1];中出现错误,因为您为参数传递了错误的值。实际上,在该行中,p为零。在循环的第一次执行中,i=0数组中A结果位置为-1,导致IndexOutOfRange异常,如下所示:

enter image description here