Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stefa168/a7ae6e2605c05f708ede87c5c0b5de43 to your computer and use it in GitHub Desktop.
Save stefa168/a7ae6e2605c05f708ede87c5c0b5de43 to your computer and use it in GitHub Desktop.
public static <E extends Comparable<E>> void quickSort(ArrayList<E> arr, int low, int high) {
if (arr == null || arr.size() == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
E pivotLength = arr.get(middle);
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr.get(i).compareTo(pivotLength) < 0) {
i++;
}
while (arr.get(j).compareTo(pivotLength) > 0) {
j--;
}
if (i <= j) {
E temp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, temp);
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment