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
| #include <iostream> #include <vector> using namespace std; void quick_sort(vector<int>* array); void quick_sort_array(vector<int>* array, int begin, int end); int find_pivot(vector<int>* array, int begin, int end); int get_partition(vector<int>* array, int begin, int end, int pivot); void Swap(int* a, int*b);
int main() { int n; cin >> n; vector<int> array; for(int i =0; i < n; i++) { int temp; cin >> temp; array.push_back(temp); } quick_sort(&array); for (int i : array) { cout << i << " "; } return 0; }
void quick_sort(vector<int>* array) { int n = (*array).size(); quick_sort_array(array, 0, n-1); }
void quick_sort_array(vector<int>* array, int begin, int end) { int pivot = find_pivot(array, begin, end); if(pivot) { int k = get_partition(array, begin, end, pivot); quick_sort_array(array, begin, k-1); quick_sort_array(array, k, end); } }
int find_pivot(vector<int>* array, int begin, int end) { int first = (*array)[begin]; for(int i = begin+1; i < end; i++) { if((*array)[i] != first) { return max(first, (*array)[i]); } } return 0; }
int get_partition(vector<int>* array, int begin, int end, int pivot) { while(begin < end) { while((*array)[begin] < pivot && begin < end) begin += 1; while((*array)[end] >= pivot && begin < end) end -= 1; if(begin < end) Swap(&(*array)[begin], &(*array)[end]); } return begin; }
void Swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
|