Advertisement
uopspop

Untitled

Feb 10th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. import java.lang.reflect.Array;
  2. import java.util.Arrays;
  3.  
  4. public class QuickSort {
  5.     public static void main(String[] args)
  6.     {
  7.         int[] ary = new int[]{40,3,59, -1, -999,4,6,99,888,7};
  8. //        int[] ary = new int[]{40};
  9. //        int[] ary = new int[]{40,-999};
  10. //        int[] ary = new int[]{40,-999,88};
  11.         myQuickSort(ary, 0, ary.length-1);
  12.         System.out.println("hey");
  13.     }
  14.  
  15.     static void myQuickSort(int[] ary, int startIndex, int endIndex){
  16.         // if the range of the sub-ary is empty or only has one element, there is no need to sort at all
  17.         if (startIndex >= endIndex) {
  18.             return;
  19.         }
  20.  
  21.         // do the sorting
  22.         Integer pivotIndex = myQuickSortHelper(ary, startIndex, endIndex);
  23.  
  24.         // divide the arrays into two sub-arrays and use the same sorting algorithm again
  25.         myQuickSort(ary, pivotIndex+1, endIndex); // right side
  26.         myQuickSort(ary, startIndex, pivotIndex-1); // left side
  27.     }
  28.  
  29.     static Integer myQuickSortHelper(int[] ary, int startIndex, int endIndex){
  30.  
  31.         // the initial last smaller value index for this round
  32.         int lastSmallerValueIndex = startIndex - 1;
  33.  
  34.         // execute the logic of quick sort
  35.         int pivotVal = ary[endIndex]; // we pick the last element of the current range of sub-array as our pivot value
  36.         for (int i = startIndex; i < endIndex; i++){
  37.             int nowVal = ary[i];
  38.             if (nowVal <= pivotVal) { // we found there is one number that is lower than the pivotValue, so we simply put it the the left side of the array
  39.                 lastSmallerValueIndex++;
  40.                 swapValInAray(ary, lastSmallerValueIndex, i);
  41.             }
  42.         }
  43.  
  44.         // put pivotValue to the pivotIndex
  45.         int pivotIndex = lastSmallerValueIndex + 1;
  46.         swapValInAray(ary, pivotIndex, endIndex);
  47.         return pivotIndex; // this is the index that is set to have the current pivotVal forever
  48.     }
  49.  
  50.     private static void swapValInAray(int[] ary, int i, int j){
  51.         int tmp = ary[i];
  52.         ary[i] = ary[j];
  53.         ary[j] = tmp;
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement