给定一个长度为 n 的整数数列,以及一个整数 k,请用快速选择算法求出数列从小到大排序后的第 k 个数。
#include <iostream> using namespace std; const int N = 100010; int a[N], n, k; int sort (int l, int r, int k) { if (l >= r) return a[l]; int x = a[(l + r) >> 1]; int i = l - 1, j = r + 1; while (i < j) { do i++; while (a[i] < x); do j--; while (a[j] > x); if (i < j) swap (a[i], a[j]); } int len = j - l + 1; if (k <= len) return sort (l, j, k); else return sort (j + 1, r, k - len); } int main () { scanf ("%d%d", &n, &k); for (int i = 0; i < n; i++) scanf ("%d", &a[i]); printf ("%d", sort (0, n - 1, k)); return 0; }
标签:do,数列,int,个数,整数,while From: https://www.cnblogs.com/leetothemoon/p/16939636.html