classSolution { public: voidprint(vector<int>& a){ for (int i: a) { cout << i << ' '; } cout << endl; }
intpartition(vector<int> &a, int start, int end){ swap(a[start], a[end]); int small = start; for (int i = start; i < end; i++) { if (a[i] < a[end]) { swap(a[i], a[small]); small++; } } swap(a[small], a[end]); // 保证small左边的数都小于samll 右边的数都大于small return small; }
voidquick_sort(vector<int>& a, int start, int end){ if (end <= start) return; int pivot = rand() % (end - start + 1) + start; // 随机选择一个主元和start交换 // 避免复杂度退化 swap(a[start], a[pivot]); int index = partition(a, start, end); quick_sort(a, start, index - 1); quick_sort(a, index + 1, end); } vector<int> sortArray(vector<int>& nums) { quick_sort(nums, 0, nums.size() - 1); cout << nums.size() << endl; return nums; } };