0

我正在尝试另一种QuickSort变体,在其中对两个ListBoxes.

这是我的代码:

class cS
{
    public static int[] mQS(int[] iar)
    {
        //divide and conquer
        if (iar.Length < 3)
        {
            if (iar.Length == 2)
            {
                if (iar[0] > iar[1])
                {
                    //wissel
                    int T = iar[1];
                    iar[1] = iar[0];
                    iar[0] = T;
                }
            }
        }
        else
        {
            int size = iar.Length;
            int sum = 0;
            int average = 0;
            for (int i = 0; i < size; i++)
            {
                sum += iar[i];
            }
            average = sum / size; 

            int lk = 1, lg = 1;
            for (int i = 0; i < size; i++)
            {
                if(iar[i]<=average)
                {
                    lk++;
                }
            else
            {
                lg++;
            }
        }

        int[] ak = new int[lk];
        int[] ag = new int[lg];
        lk--; lg--;

        for (int i = 0; i < average; i++)
        {
            if (iar[i] <= average)
            {
                ak[lk]=iar[i];
                lk--; 
            }
            else
            {
                ag[lg] = iar[i];
                lg--;
            }
        }

        if (!Allegelijk(ak)) {ak= mQS(ak);}
        if(!Allegelijk(ag)) {ag = mQS(ag);}
        // plak weer aan elkaar in iar
        for (int i = 0; i < ak.Length; i++)
        {
            iar[i] = ak[i];
        }
        for (int i = 0; i < ag.Length; i++)
        {
            iar[i + ak.Length] = ag[i];
        }
    }
    return iar;
}

private static  bool allEqual(int[] ar)
{
    bool bG = true;
    for (int i = 1; i < ar.Length; i++)
    {
        if (ar[i] != ar[0])
        {
            bG = false;
            break;
        }
     }
     return bG;
 }

}

}

但是在运行时出现此错误:

index out of range exception at the line :

  if (iar[i] <= average>

谁能解释发生了什么以及如何解决它?

4

2 回答 2

1

来自评论:

该行for (int i = 0; i < average; i++)应该size没有average

于 2013-02-01T14:29:38.187 回答
0

在执行过程中的某个时刻, 的值sum变得足够大,以至于average等于的值sum / size变得大于iar.Length。因此,ifor 循环中的值最终会达到大于或等于 的值iar.Length

于 2013-02-01T14:29:03.950 回答