Main Page   Class Hierarchy   Alphabetical List   Compound List   File List   Compound Members  

Quicksort.java

Go to the documentation of this file.
00001 // file:   Quicksort.java
00002 // author: Robert Keller
00003 // purpose: Define Quicksort algorithm that can be used with arbitrary
00004 //          Objects and a Comparator.
00005 
00006 
00007 /**
00008  * Quicksort is a setup for sorting an array of objects using the Quicksort
00009  * algorithm.  Comparisons are done with an arbitrary Compartor.
00010  */
00011 
00012 public class Quicksort
00013   {
00014   /**
00015    * The array of Objects to be sorted.
00016    */
00017 
00018   private Object a[];
00019 
00020 
00021   /**
00022    * Constructor for the Quicksort setup
00023    * @param the array of objects to be sorted
00024    */
00025 
00026   public Quicksort(Object array[])
00027     {
00028     a = array;
00029     }
00030 
00031 
00032   /**
00033    * Sort the array in place using the argument comparator
00034    */
00035 
00036   public void sort(java.util.Comparator comp)
00037     {
00038     sort(0, a.length-1, comp);
00039     }
00040 
00041 
00042   /**
00043    *  Sort the array elements at indices from low to high, inclusive.
00044    */
00045 
00046   public void sort(int low, int high, java.util.Comparator comp)
00047     {
00048     if( low >= high )
00049       return;                           // basis case, <= 1 element
00050 
00051     Object pivot = a[(low + high)/2];   // select pivot
00052 
00053     // shift elements <= pivot to bottom
00054     // shift elements >= pivot to top
00055 
00056     int i = low-1;
00057     int j = high+1;
00058 
00059     for( ; ; )
00060       {                             // find two elements to exchange
00061       do { i++; } while( comp.compare(a[i], pivot) < 0 );       // slide i up
00062       do { j--; } while( comp.compare(a[j], pivot) > 0 );       // slide j down
00063 
00064       if( i >= j ) break;                       // if sliders meet or cross
00065 
00066       swap(i, j);                   // swap elements and continue
00067       }
00068 
00069     sort(low, i-1, comp);     // sort lower half
00070     sort(j+1, high, comp);    // sort upper half
00071     }
00072 
00073 
00074   /**
00075    *  swap(i, j) interchanges the values in a[i] and a[j]
00076    */
00077 
00078   public void swap(int i, int j)
00079     {
00080     Object temp = a[i];
00081     a[i] = a[j];
00082     a[j] = temp;
00083     }
00084 }

Generated at Wed Feb 19 23:28:36 2003 for OpenList by doxygen1.2.6 written by Dimitri van Heesch, © 1997-2001