-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
rselect.c
77 lines (74 loc) · 1.39 KB
/
rselect.c
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
int part(int a[], int l, int r, int n, int pivot, int pindex)
{
int p1 = l, p2 = r;
while (p2 > p1)
{
if (a[p1] > pivot && a[p2] < pivot)
{
swap(&a[p1], &a[p2]);
}
else
{
if (a[p1] <= pivot)
{
p1++;
}
if (a[p2] >= pivot)
{
p2--;
}
}
}
swap(&a[pindex], &a[p2]);
return p2;
}
int rselect(int a[], int l, int r, int n, int o)
{
int pivot, pindex, pactual;
if (r > l)
{
pindex = rand() % (r - l + 1);
pivot = a[pindex];
pactual = part(a, l, r, n, pivot, pindex);
if (pactual == o)
{
return a[pactual];
}
if (o < pactual)
{
rselect(a, l, pactual - 1, n, o);
}
if (o > pactual)
{
rselect(a, pactual + 1, r, n, o - pactual);
}
}
if (r == l)
{
return a[l];
}
return -1;
}
int main()
{
srand(time(NULL));
int n, o, i, *a;
scanf("%d %d", &n, &o);
a = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{
scanf("%d", a + i);
}
printf("\n\n%d", rselect(a, 0, n - 1, n, o));
return 0;
}