我正在尝试另一种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>
谁能解释发生了什么以及如何解决它?