Skip to content

Instantly share code, notes, and snippets.

@maxkibble
Last active July 1, 2018 08:11
Show Gist options
  • Select an option

  • Save maxkibble/757153a9c8fe146d3a8c098ad14a3aa1 to your computer and use it in GitHub Desktop.

Select an option

Save maxkibble/757153a9c8fe146d3a8c098ad14a3aa1 to your computer and use it in GitHub Desktop.
c++ implementation for quick-sort algorithm
void quickSort(int *a, int l, int r) {
if (l >= r) return;
// this is a good coding style to avoid overflow
int mid = l + (r - l) / 2;
// choose a[mid] as pivot to speed up for sequences in order
int pivot = a[mid];
std::swap(a[mid], a[r]);
int i = l, j = r - 1;
while (i <= j) {
while (i <= j && a[i] <= pivot) i++;
while (i <= j && a[j] > pivot) j--;
if (i < j) std::swap(a[i], a[j]);
}
std::swap(a[r], a[i]);
quickSort(a, l, i - 1);
quickSort(a, i + 1, r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment