Problem with Quick Sort Algorithm

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;

   }
}
+3
source share
2 answers

I am surprised that the code you posted ever works or even ends. Test:

(tooBigIndex < n) &&

should be explicit

(tooBigIndex < first + n) &&

and index in rows:

   t= data[0];
   data[0]= data[tooSmallIndex];
   data[tooSmallIndex]=t;

first, 0 ( , pivot t - , - ; -).

, , ; -).

+7

, , ( , ).

, IComparable Array.sort(). , IComparable, - :

int[] valArray = new int[6] { 1, 5, 2, 6, 9, 7 };
Array.Sort (valArray);                            // <-- This is all you need.
String s = "";
foreach (int val in valArray)
    s += "," + val;
MessageBox.Show (s.Substring(1));

:

1,2,5,6,7,9

, QuickSort . - , , ( ) , .

+3

Source: https://habr.com/ru/post/1751849/


All Articles