Skip to content

Instantly share code, notes, and snippets.

@wang-nima
Created September 28, 2015 20:44
Show Gist options
  • Save wang-nima/d36f52413a42c816e782 to your computer and use it in GitHub Desktop.
Save wang-nima/d36f52413a42c816e782 to your computer and use it in GitHub Desktop.
quicksort
#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