Commonly used practice with Quick Sort

  • Commonly used practice when using Quick Sort:

      public static void main(String[] args)
      {
          String[] A = ..... ; // Array to be sorted with Quick Sort
    
          // shuffle array A
          for ( int k = 0; k < N; k++ )
          {
             int i = Math.random()*A.length;
    	 int j = Math.random()*A.length;
    	 exch(A, i, j);
          }
    
          QuickSort(A, 0, A.length, H);
      }
    

  • Why shuffle:

    • Make Quick Sort avoid picking the smallest value as pivot all the time...

    • Help Quick Sort achieve the average running time performance with a randomized input array

Increase the likelihood to partition the array into 2 equal halves

  • The best pivot value is the median of the input array

    Example:

     A[] =   [ 5   3   7   2   8   4   1   9   6 ]
                               |
    			   | partition( )
                               V
     A[] =   [ 3   2   4   1   5   7   8   9   6 ]
    

  • We can improve the likelihood of picking the median by considering 3 (random value) selected from the input array:
    (Instead of always using the first element as pivot)

    The median of 3 partitioning method:

     A[] =    [ X  ..  ..  ..  ..  ..  Y  ..  ..  ..  ..  ..  Z ]
    
     Let M = median(X,Y,Z)
    
        (1) Swap(X, M)
        (2) Then call partition( )
    

How to find the median of 3 values

  • Easy to understand algorithm:

        public static int medianOf3(int a, int b, int c)
        {
            if ( (b <= a && a <= c) || (c <= a && a <= b) )
                return a;
    
            if ( (a <= b && b <= c) || (c <= b && b <= a) )
                return b;
    
            return c;
        }
    

  • Faster algorithm using exclusive OR (^):

        public static int medianOf3(int a, int b, int c)
        {
            if ( (a > b) ^ (a > c) )   // Either a > b or a > c
                return a;
    
            if ( (b > a) ^ (b > c) )   // Either b > a or b > c
                return b;
    
            return c;
        }
    

DEMO: demo/14-sort/15-median-of-3/Demo.java + Demo2.java