快速选择算法基于快速排序算法,用于求解第k小的数,它的时间复杂度为O(n)。
算法步骤如下:
//nums为原数组
//返回第k小的数,k从1开始
int quick_select(vector<int> &nums, int l, int r, int k) {
if (l == r) {
return nums[l];
}
int x = nums[(l+r)/2];
int i = l - 1, j = r + 1;
while (i < j) {
do i++; while (nums[i] < x);
do j--; while (nums[j] > x);
if (i < j) {
swap(nums[i], nums[j]);
}
}
int sl = j - l + 1;
if (sl >= k) {
return quick_select(nums, l, j, k);
} else {
return quick_select(nums, j+1, r, k-sl);
}
}