Advertisement
nate23nate23

hw 17 failure

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