数列中的第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;
}
``````
————————

``````#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;
}
``````