Visual Studio를 사용하여 C#에서 재귀 빠른 방법을 작성했습니다. 이상하게 생각되는 것은, 정렬 될 숫자의 모음 인 입력이 배열에서 9500보다 낮 으면 최상, 최악 및 최다의 결과 모두에서 결과를 제공한다는 것입니다. 그러나 입력이 9500보다 클 경우 stackoverflow 예외가 발생합니다. 나는 현장에서 내 질문과 거의 같은 또 다른 질문이 있다는 것을 알고 있지만 재귀적인 조건을 만들었다.재귀 Quicksort가 스택 오버플로 예외를 throw합니다.
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();
}
실망 할 필요가 없습니다! –
재귀 알고리즘이 스택 오버플로를 얻으면 일반적으로 하단 사례에 대한 테스트가 올바르지 않다는 것을 의미합니다. – Barmar
-1 CAPS LOCK ... – sashoalm