Last active
January 16, 2021 08:53
-
-
Save changhengliou/b6ee18431f7c0f5815cf40f92aa8f4b7 to your computer and use it in GitHub Desktop.
Quick sort
This file contains 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
#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