快速選擇 第k個數
阿新 • • 發佈:2022-05-15
快速選擇 第k個數
題目描述
給定一個序列,求第k小的數
演算法思想
利用快速排序思想,演算法複雜度能達到O(n)步驟如下:
1.找到排序分界點x,這裡選擇區間最左值
2.排序,讓左邊的值都小於x,右邊都大於x
3.遞迴排序尋找數字,如果左區間數字數目大於k,直接在左邊找第k小的數字,如果左區間數字數目小於k,則在右邊找
模板
#include<bits/stdc++.h> using namespace std; int n, k; const int maxn = 1e5 + 10; int a[maxn]; int quickSort(int l, int r, int k) { if (l == r) return a[l]; int x = a[l], i = l - 1, j = r + 1; while (i < j) { while (a[++i] < x); while (a[--j] > x); if (i < j) swap(a[i], a[j]); } int ls = j - l + 1; if (k <= ls) return quickSort(l, j, k); return quickSort(j + 1, r, k - ls); } int main() { scanf("%d%d", &n, &k); for (int i = 0; i < n; i++) scanf("%d", &a[i]); cout << quickSort(0, n - 1, k); return 0; }