Hey all,
I'm working on a quick sort algorithm in C#, but I'm facing a strange problem which is, among 10 times of executing the algorithm on random numbers, I got 2 or 3 wrong sorting answers.
I mean: this code can sort about 7 out of 10 examples; why? I couldn't figure out what's the problem, can you help me?
public void quicksort(int[] data, int first, int n)
{
int pivotIndex, n1, n2;
if (n > 1)
{
pivotIndex= partition(data, first, n);
n1 = pivotIndex-first;
n2 = n -n1 -1;
quicksort(data, first, n1);
quicksort(data, pivotIndex+ 1, n2);
}
}
private int partition(int[] data, int first, int n)
{
int t;
int pivot= data[first], tooBigIndex=first+1, tooSmallIndex=first+n-1;
while (tooBigIndex<= tooSmallIndex)
{
while( (tooBigIndex < n) && (data[tooBigIndex] <= pivot) )
tooBigIndex++;
while (data[tooSmallIndex] > pivot)
tooSmallIndex--;
if (tooBigIndex< tooSmallIndex)
{
t = data[tooBigIndex];
data[tooBigIndex] = data[tooSmallIndex];
data[tooSmallIndex] = t;
tooSmallIndex--;
tooBigIndex++;
}
}
t= data[0];
data[0]= data[tooSmallIndex] ;
data[tooSmallIndex]=t;
return tooSmallIndex;
}
}