三、阅读程序-2
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 30 31 32 33 34 35 36 | #include <iostream> #include <cstdlib> using namespace std; int n; int d[10000]; int find(int L, int R, int k) { int x = rand() % (R - L + 1) + L; swap(d[L], d[x]); int a = L + 1, b = R; while (a < b) { while (a < b && d[a] < d[L]) ++a; while (a < b && d[b] >= d[L]) --b; swap(d[a], d[b]); } if (d[a] < d[L]) ++a; if (a - L == k) return d[L]; if (a - L < k) return find(a, R, k - (a - L)); return find(L + 1, a - 1, k); } int main() { int k; cin >> n; cin >> k; for (int i = 0; i < n; ++i) cin >> d[i]; cout << find(0, n - 1, k); return 0; } |
假设输入的 n,k和 d[i]都是不超过 10000 的正整数,且 k 不超过 n,并假设 rand() 函数产生的是均匀的随机数,完成下面的判断题和单选题:
