Skip to content

Instantly share code, notes, and snippets.

@ricardovogel
Last active December 21, 2018 10:57
Show Gist options
  • Save ricardovogel/616cde89816efa83b7d9d758d1392d93 to your computer and use it in GitHub Desktop.
Save ricardovogel/616cde89816efa83b7d9d758d1392d93 to your computer and use it in GitHub Desktop.
in place quicksort
public static void quickSort(int[] elements) {
quickSort(elements, 0, elements.length - 1);
}
public static void quickSort(int[] elements, int low, int high) {
if(low >= high){
return;
}
int pivot = partition(elements, low, high);
quickSort(elements, low, pivot - 1);
quickSort(elements, pivot + 1, high);
}
public static int partition(int[] elements, int low, int high) {
int left = low;
int right = high - 1;
int pivot = elements[high];
while(left <= right){
while (left <= right && elements[left] < pivot){
left++;
}
while (left <= right && elements[right] > pivot){
right--;
}
if(left <= right){
swap(elements, left, right);
left++;
right--;
}
}
swap(elements, left, high);
return left;
}
public static void swap(int[] elements, int a, int b) {
int temp = elements[a];
elements[a] = elements[b];
elements[b] = temp;
}
public static void printArr(int[] arr){
String str = "";
for(int i : arr){
str += i + ", ";
}
System.out.println(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment