Last active
December 21, 2018 10:57
-
-
Save ricardovogel/616cde89816efa83b7d9d758d1392d93 to your computer and use it in GitHub Desktop.
in place quicksort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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