Thibstars

QuickSort

Sep 21st, 2016
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. public class QuickSort {
  2.     private Comparable[] comparables;
  3.     private int number;
  4.  
  5.     public void sort(Comparable[] values) {
  6.         //Check for empty or null array
  7.         if (values ==null || values.length==0){
  8.             return;
  9.         }
  10.         this.comparables = values;
  11.         number = values.length;
  12.         quicksort(0, number - 1);
  13.     }
  14.  
  15.     private void quicksort(int low, int high) {
  16.         int i = low, j = high;
  17.         //Get the pivot element from the middle of the list
  18.         Comparable pivot = comparables[low + (high-low)/2];
  19.  
  20.         //Divide into two lists
  21.         while (i <= j) {
  22.             //If the current value from the left list is smaller then the pivot
  23.             // element then get the next element from the left list
  24.             while (comparables[i].compareTo(pivot) < 0) {
  25.                 i++;
  26.             }
  27.             //If the current value from the right list is larger then the pivot
  28.             // element then get the next element from the right list
  29.             while (comparables[j].compareTo(pivot) > 0) {
  30.                 j--;
  31.             }
  32.  
  33.             //If we have found a values in the left list which is larger then
  34.             // the pivot element and if we have found a value in the right list
  35.             // which is smaller then the pivot element then we exchange the
  36.             // values.
  37.             // As we are done we can increase i and j
  38.             if (i <= j) {
  39.                 exchange(i, j);
  40.                 i++;
  41.                 j--;
  42.             }
  43.         }
  44.         //Recursion
  45.         if (low < j)
  46.             quicksort(low, j);
  47.         if (i < high)
  48.             quicksort(i, high);
  49.     }
  50.  
  51.     private void exchange(int i, int j) {
  52.         Comparable temp = comparables[i];
  53.         comparables[i] = comparables[j];
  54.         comparables[j] = temp;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment