voidquick_sort(int q[], int l, int r){ if (l >= r) return int i = l - 1; int r = r + 1; int x = q[l + r >>1]; while (i < j){ do i++; while(q[i] < x); do j--; while(q[j] > x); if(i < j) swap(q[i], q[j]); } quick_sort(q, l, j); quick_sort(q, j + 1, r); }
while循环结束后,q[l…j] <= x,q[j+1…r] >= x
注:q[l…j] <= x意为q[l],q[l+1]…q[j-1],q[j]的所有元素都<= x
最小k个数
classSolution { public: vector<int> res; voidquick_sort(vector<int>& arr, int l, int r, int k){ if (l >= r) return; int i = l - 1, j = r + 1; int x = arr[l + r >> 1]; while (i < j) { do i++; while (arr[i] < x); do j--; while (arr[j] > x); if (i < j) swap(arr[i], arr[j]); } int n = j - l + 1; if (n > k) quick_sort(arr, l, j, k); elseif (n == k) { for (int m = 0; m < k; m++) { res.push_back(arr[l + m]); } } else { for (int m = 0; m < n; m++) { res.push_back(arr[l + m]); } if (j + 1 == r) //注意这个情况 res.push_back(arr[r]); else quick_sort(arr, j + 1, r, k - n); } } vector<int> smallestK(vector<int>& arr, int k) { quick_sort(arr, 0, arr.size() - 1, k); return res; } };