Skip to content

Instantly share code, notes, and snippets.

@kingdido999
Last active January 11, 2016 19:26
Show Gist options
  • Save kingdido999/450d31e2ff691c695655 to your computer and use it in GitHub Desktop.
Save kingdido999/450d31e2ff691c695655 to your computer and use it in GitHub Desktop.
A Quicksort implementation in Java which uses the first number as pivot.
/* Inspired by: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheQuickSort.html */
void quickSort(int[] a, int first, int last) {
if (first < last) {
int p = partition(a, first, last); // split point
quickSort(a, first, p - 1); // sort numbers on the left side of the split point
quickSort(a, p + 1, last); // sort numbers on the right side of the split point
}
}
int partition(int[] a, int first, int last) {
int pivot = a[first]; // choose the first number as pivot value
int left = first + 1;
int right = last;
while (left <= right) {
// find numbers that should be swapped
while (a[left] < pivot) left++;
while (a[right] > pivot) right--;
if (left < right) {
// swap left and right
swap(a, left, right);
} else {
// swap pivot and right, and return right index as the split point
swap(a, first, right);
return right;
}
}
}
void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment