Skip to content

Instantly share code, notes, and snippets.

@changhengliou
Last active January 16, 2021 08:53
Show Gist options
  • Save changhengliou/b6ee18431f7c0f5815cf40f92aa8f4b7 to your computer and use it in GitHub Desktop.
Save changhengliou/b6ee18431f7c0f5815cf40f92aa8f4b7 to your computer and use it in GitHub Desktop.
Quick sort
#include <vector>
using namespace std;
void quick_sort(vector<int>& arr, int l, int r);
int quick_partition(vector<int>& arr, int l, int r);
int quick_partition(vector<int>& arr, int l, int r) {
int pivot = (l + r) >> 1;
swap(arr[pivot], arr[r]);
int index = l;
for (int i = l; i <= r - 1; i++) {
if (arr[i] <= arr[pivot]) {
swap(arr[i], arr[index++]);
}
}
swap(arr[r], arr[index]);
return index;
}
void quick_sort(vector<int>& arr, int l, int r) {
if (l >= r) return;
int m = quick_partition(arr, l, r);
quick_sort(arr, l, m - 1);
quick_sort(arr, m + 1, r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment