Advertisement
nate23nate23

hw 17 failure

Dec 2nd, 2015
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1.  
  2. /**
  3.  * Nate Wheeler
  4.  * hw 17
  5.  * compsci220
  6.  * dec 2, 2015
  7.  *
  8.  */
  9. public class QuickSort2 {
  10.           public static void quickSort(int[] list) {
  11.             quickSort(list, 0, list.length - 1);
  12.           }
  13.  
  14.           private static void quickSort(int[] list, int first, int last) {
  15.             if (last > first) {
  16.               int pivotIndex = partition(list, first, last);
  17.               quickSort(list, first, pivotIndex - 1);
  18.               quickSort(list, pivotIndex + 1, last);
  19.             }
  20.           }
  21.           //private static int medianOf3(int middle, int first, int last)
  22.  
  23.           /** Partition the array list[first..last] */
  24.           private static int partition(int[] list, int first, int last) {
  25.             int middle= list[(first+last)/2];
  26.             int pivot; // Choose the first element as the pivot\
  27.             if(first<middle && middle<last)
  28.                 pivot=middle;
  29.             if(first<last && middle>last)
  30.                 pivot=last;
  31.             else
  32.                 pivot=first;
  33.             int low = first; // Index for forward search
  34.             int high = last; // Index for backward search
  35.  
  36.             while (high > low) {
  37.               // Search forward from left
  38.               while (low <= high && list[low] <= pivot)
  39.                 low++;
  40.  
  41.               // Search backward from right
  42.               while (low <= high && list[high] > pivot)
  43.                 high--;
  44.  
  45.               // Swap two elements in the list
  46.               if (high > low) {
  47.                 int temp = list[high];
  48.                 list[high] = list[low];
  49.                 list[low] = temp;
  50.               }
  51.             }
  52.  
  53.             while (high > first && list[high] >= pivot)
  54.               high--;
  55.  
  56.             // Swap pivot with list[high]
  57.             if (pivot > list[high]) {
  58.               list[first] = list[high];
  59.               list[high] = pivot;
  60.               return high;
  61.             }
  62.             else {
  63.               return first;
  64.             }
  65.           }
  66.  
  67.           /** A test method */
  68.           public static void main(String[] args) {
  69.             int[] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};
  70.             quickSort(list);
  71.             for (int i = 0; i < list.length; i++)
  72.               System.out.print(list[i] + " ");
  73.           }
  74.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement