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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <iostream> #include <vector> #include <cstdlib> #include <ctime> #include <sstream> #define random(a,b) (rand()%(b-a)+a) using namespace std;
bool intRandomRange(vector<int>& res, int min, int max, int count) { srand((int)time(0)); for (int i = 0; i < count; i++) { res.push_back((int)random(min, max)); } return true; }
string vector2string(vector<int>& vec) { stringstream ss; for (int i = 0; i < vec.size(); ++i) { if (i != 0) ss << ","; ss << vec[i]; } return ss.str(); } bool contrastByOrder(int left, int right, bool bigger, bool equal) { if (equal) if (bigger) return left >= right; else return left <= right; else if (bigger) return left > right; else return left < right; }
int quickSort_main(vector<int>& vec, int left, int right, bool ascending) { int mid = left++; while (left <= right) { while (left <= right && contrastByOrder(vec[right], vec[mid], ascending, false)) right--; if (left <= right) { swap(vec[mid], vec[right]); mid = right; } while (left <= right && contrastByOrder(vec[mid], vec[left], ascending, true)) left++; if (left <= right) { swap(vec[mid], vec[left]); mid = left; } } return mid; }
void quickSort_Rp(vector<int>& vec, int left, int right, bool ascending) { if (left > right) return; int mid = quickSort_main(vec, left, right, ascending); quickSort_Rp(vec, left, mid - 1, ascending); quickSort_Rp(vec, mid + 1, right, ascending); }
bool quickSort(vector<int>& vec, bool ascending) { int count = vec.size(); if (count <= 1) return false; quickSort_Rp(vec, 0, vec.size() - 1, ascending); return true; }
int main() { vector<int> test; intRandomRange(test, 0, 10, 10); cout << vector2string(test) << endl; if (quickSort(test, false)) cout << vector2string(test) << endl; else cout << "No Need to Quick Sort" << endl; }
|