Last active
July 1, 2018 08:11
-
-
Save maxkibble/757153a9c8fe146d3a8c098ad14a3aa1 to your computer and use it in GitHub Desktop.
c++ implementation for quick-sort algorithm
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
| 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