forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSelection.cpp
More file actions
57 lines (51 loc) · 669 Bytes
/
Selection.cpp
File metadata and controls
57 lines (51 loc) · 669 Bytes
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <cstdio>
#define ELEMENT_COUNT 10000
using namespace std;
int n, k, d[ELEMENT_COUNT];
int partition(int l, int r)
{
int x = d[r], j = l - 1;
for (int i = l; i <= r; i++)
{
if (d[i] <= x)
{
j++;
int temp = d[i];
d[i] = d[j];
d[j] = temp;
}
}
return j + 1;
}
int select(int k)
{
int l = 0, r = n - 1;
while (l < r)
{
int ord = partition(l, r);
if (ord < k)
{
l = ord;
}
else if (ord > k)
{
r = ord - 2;
}
else
{
return d[ord - 1];
}
}
return d[l];
}
int main()
{
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++)
{
scanf("%d", &d[i]);
}
int kth = select(k);
printf("%d", kth);
return 0;
}