Advertisement
Guest User

quicksort

a guest
Jan 21st, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. class Solution {
  2.   /**
  3.    * @param elements
  4.    *     Array of integers to be sorted.
  5.    */
  6.   public static void quickSort(int[] elements) {
  7.     if(elements == null || elements.length < 2) {
  8.       return;
  9.     }
  10.     sort(elements, 0, elements.length-1);
  11.   }
  12.  
  13.   public static void sort(int[] arr, int low, int high) {
  14.     if (high > low) {
  15.       int pos = partition(arr, low, high);
  16.       sort(arr, low, pos-1);
  17.       sort(arr, pos+1, high);
  18.     }
  19.   }
  20.   public static int partition(int[] arr, int low, int high) {
  21.     int pivot = arr[high];
  22.     int i = low-1;
  23.    
  24.     for(int j = low; j < high; j++) {
  25.       if (arr[j] < pivot) {
  26.         i++;
  27.         int temp = arr[i];
  28.         arr[i] = arr[j];
  29.         arr[j] = temp;
  30.       }
  31.     }
  32.     int temp = arr[i+1];
  33.     arr[i+1] = arr[high];
  34.     arr[high] = temp;
  35.    
  36.     // for(int j = 0; j < arr.length; j++) {
  37.     //   System.out.print(arr[j] + ", ");
  38.     // }
  39.     // System.out.print(i+1);
  40.     // System.out.println();
  41.     return i+1;
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement