我已經使用Visual Studio在c#中編寫了遞歸快速排序算法。奇怪的是,當輸入是將要排序的數字的集合時,它的排列數低於9500,它會給出最好,最差和平均情況下的結果。但是,當輸入大於9500時,會拋出一個堆棧溢出異常。我知道還有另一個問題與我在網站上的問題幾乎相同,但是我也做了遞歸的條件。遞歸Quicksort引發堆棧溢出異常
public int[] quick(int [] myarray,int p,int r)
{
int q;
if (p < r)
{
q = partition(myarray, p, r);
quick(myarray, p, q - 1);
quick(myarray, q + 1, r);
}
return myarray;
}
public int partition(int [] myarray, int left, int right)
{
int i = left - 1;
int tmp = 0;
int pivot = myarray[right];
for (int j = left; j < right; j++)
{
if (myarray[j] < pivot)
{
i = i + 1;
tmp = myarray[i];
myarray[i] = myarray[j];
myarray[j] = tmp;
}
}
tmp = myarray[i + 1];
myarray[i + 1] = myarray[right];
myarray[right] = tmp;
return i + 1;
}
static void Main(string[] args)
{
Stopwatch mwatch = new Stopwatch();
Program quickprogram = new Program();
int[] mydizi = new int[9000];
//int counter = 9000;
//initialization of quick array
for (int i = 0; i < mydizi.Length; i++)
{
mydizi[i] = i + 1;
}
int[] result = new int[9000]; //return array
//time is starting
mwatch.Start();
//algorithm is called
result = quickprogram.quick(mydizi,0,mydizi.Length-1);
//result is returned from quickprogram
for (long j = 0; j < result.Length;j++)
{
Console.Write(result[j] + ",");
}
mwatch.Stop();
//time is up
//Printing the time that show how it takes
Console.Write("Ms:" + mwatch.Elapsed.Milliseconds + " S:" + mwatch.Elapsed.Seconds + " Mn:" + mwatch.Elapsed.Minutes + " Hr:" + mwatch.Elapsed.Hours);
Console.ReadLine();
}
不需要! – 2014-10-19 08:28:08
如果遞歸算法得到堆棧溢出,通常意味着您對底部情況的測試不正確。 – Barmar 2014-10-19 08:29:35
-1 CAPS LOCK ... – sashoalm 2014-10-19 08:29:40