I am working on a fast sorting algorithm in C #, but I had a strange problem, which is that among 10 times the algorithm was executed on random numbers, I received 2 or 3 incorrect sort answers.
I mean: this code can sort about 7 out of 10 examples; What for? I could not understand what the problem is, 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;
}
}
source
share