1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <iostream> #include <vector> using namespace std;
void QuickSort(vector<int>& vec, int left, int right); int Partition(vector<int>& vec, int left, int right); void Print(const vector<int>& vec);
int main() { vector<int> vec = { 49, 38, 65, 97, 76, 13, 27, 49 }; cout << "before sort:" << endl; Print(vec); cout << "sort:" << endl; QuickSort(vec, 0, vec.size() - 1); cout << "after sort:" << endl; Print(vec); return 0; }
void QuickSort(vector<int>& vec, int left, int right) { if( left >= right ) return;
int mid = Partition(vec, left, right);
QuickSort(vec, left, mid - 1); QuickSort(vec, mid + 1, right); }
int Partition(vector<int>& vec, int left, int right) { int pivot = vec[left];
while( left < right ) { while( left < right && vec[right] >= pivot ) right--; if( left < right ) vec[left] = vec[right]; while( left < right && vec[left] <= pivot ) left++; if( left < right ) vec[right] = vec[left]; }
vec[left] = pivot;
Print(vec);
return left; }
void Print(const vector<int>& vec) { for( int v : vec ) { cout << v << " "; } cout << endl; }
|