-
-
Save wang-nima/d36f52413a42c816e782 to your computer and use it in GitHub Desktop.
quicksort
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
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
int partition(vector<int> &v, int low, int high) { | |
int pivot = v[low]; | |
int index = low + 1; | |
for (int i = low + 1; i <= high; i++) { | |
if (v[i] < pivot) { | |
swap(v[i], v[index]); | |
index++; | |
} | |
} | |
swap(v[index-1], v[low]); | |
return index-1; | |
} | |
void quickSort(vector<int> &v, int low, int high) { | |
if (low < high) { | |
int pivot = partition(v, low, high); | |
quickSort(v, low, pivot-1); | |
quickSort(v, pivot+1, high); | |
} | |
} | |
int main() { | |
vector<int> v = {4,2,1,5,6}; | |
quickSort(v, 0, v.size()-1); | |
for (auto i : v) { | |
cout << i << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment