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
| class Solution { public: vector<int> sortArray(vector<int>& nums) { int n = nums.size(); quickSort(nums, 0, n - 1); return nums; } void quickSort(vector<int>& nums, int l, int r) { if (l < r) { int j = patition(nums, l, r); quickSort(nums, l, j - 1); quickSort(nums, j + 1, r); } } int patition(vector<int>& nums, int l, int r) { int pivot = l + rand() % (r - l + 1); int t = nums[pivot]; swap(nums[pivot], nums[l]); int i = l, j = r; while (i < j) { while (j > i && nums[j] >= t) j--; while (i < j && nums[i] <= t) ++i; if (i < j) swap(nums[i], nums[j]); } swap(nums[j], nums[l]); return j; } };
|