Skip to content

Instantly share code, notes, and snippets.

@anishLearnsToCode
Last active January 17, 2022 21:29
Show Gist options
  • Save anishLearnsToCode/9bc167de47488c229564fce43858d23f to your computer and use it in GitHub Desktop.
Save anishLearnsToCode/9bc167de47488c229564fce43858d23f to your computer and use it in GitHub Desktop.

Quicksort

public static void quickSort(int[] array) {
   quickSort(array, 0, array.length - 1);
}

private static void quickSort(int[] arr, int begin, int end) {
   if (begin < end) {
       int partitionIndex = partition(arr, begin, end);
       quickSort(arr, begin, partitionIndex - 1);
       quickSort(arr, partitionIndex + 1, end);
   }
}

private static int partition(int[] array, int left, int right) {
   int pivot = array[right], i = left - 1;
   for (int j = left ; j < right ; j++) {
       if (array[j] < pivot) {
           i++;
           swap(array, i, j);
       }
   }
   swap(array, i + 1, right);
   return i + 1;
}

private static void swap(int[] array, int i, int j) {
   int temp = array[i];
   array[i] = array[j];
   array[j] = temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment