-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorder.c
69 lines (62 loc) · 1.39 KB
/
order.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
/*
Infoarena statistic order problem
(n_th element is implemented in algorithm header)
complexity: on averege O(n), in worst case scenario O(n^2)
Idea: We use QuickSort algorithm to determine the solution.
We observe that it is not necessarily to sort the whole array and it's
enough to sort some parts of the array (those that are relevant to our problem)
*/
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <ctime>
#define N 3000009
using namespace std;
int n, k, a[N];
int quickSort(int left, int right)
{
int mid = left + rand() % (right - left + 1) ;
int swapedElement = a[mid];
int i = left, j = right ;
while (i <= j)
{
while (a[i] < swapedElement)
i++;
while (a[j] > swapedElement)
j--;
if (i < j) {
swap(a[i], a[j]);
i++, j--; // we can swap the same element and this case will cause an infinite loop
}
else
return j;
}
return 0;
}
void stat(int left, int right, int k)
{
if (left == right)
return;
int pivot_position = quickSort(left, right);
int dist = pivot_position - left + 1;
if (dist >= k)
stat(left, pivot_position, k);
else
stat(pivot_position + 1, right, k - dist);
}
int main()
{
srand(time(NULL));
fstream g;
FILE *f;
f = fopen("sdo.in", "rt");
g.open("sdo.out", ios::out);
fscanf(f, "%d%d", &n, &k);
int i;
for (i = 1; i <= n; i++)
fscanf(f, "%d", &a[i]);
stat(1, n, k);
g << a[k];
return 0;
}