Advertisement
lubaochuan

Untitled

Oct 26th, 2011
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. public static <T extends Comparable<? super T>> void quickSort(T[] data, int min, int max) {
  2.     int indexofpartition;
  3.  
  4.     if (max > min) {
  5.         /** Create partitions */
  6.         indexofpartition = findPartition(data, min, max);
  7.  
  8.         /** Sort the left side */
  9.         quickSort(data, min, indexofpartition - 1);
  10.  
  11.         /** Sort the right side */
  12.         quickSort(data, indexofpartition + 1, max);
  13.     }
  14. }
  15.  
  16. private static <T extends Comparable<? super T>> int findPartition(T[] data, int min, int max) {
  17.     int left, right;
  18.     T temp, partitionelement;
  19.     int middle = (min + max) / 2;
  20.  
  21.     partitionelement = data[middle]; // use middle element as partition            
  22.     left = min;
  23.     right = max;
  24.  
  25.     while (left < right) {
  26.         /** search for an element that is > the partitionelement */
  27.         while (data[left].compareTo(partitionelement) < 0) {
  28.             left++;
  29.         }
  30.  
  31.         /** search for an element that is < the partitionelement */
  32.         while (data[right].compareTo(partitionelement) > 0 ) {
  33.             right--;
  34.         }
  35.  
  36.         /** swap the elements  */
  37.         temp = data[left];
  38.         data[left] = data[right];
  39.         data[right] = temp;
  40.            
  41.         /** let left skip elements with the same value as the partition element */                                                
  42.         if(data[left].compareTo(data[right]) == 0
  43.                 && left != right){
  44.             left++;
  45.         }
  46.     }
  47.     return right;
  48. }
  49.  
  50.  
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement