forked from derekhh/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-median.cpp
More file actions
52 lines (47 loc) · 898 Bytes
/
find-median.cpp
File metadata and controls
52 lines (47 loc) · 898 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
//find-median.cpp
//Find the Median
//Algorithms - Search
//Author: derekhh
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
int a[1000002];
int partition(int ar[], int l, int r)
{
int idx = rand() % (r - l + 1) + l;
swap(ar[idx], ar[r]);
int pivot = ar[r], cur = l;
for (int i = l; i < r; i++)
if (a[i] <= pivot)
swap(a[i], a[cur++]);
swap(ar[r], ar[cur]);
return cur;
}
int quicksort(int ar[], int l, int r, int idx)
{
if (l < r)
{
int m = partition(ar, l, r);
if (idx == m - l + 1) return ar[m];
else if (idx <= m - l)
return quicksort(ar, l, m - 1, idx);
else
return quicksort(ar, m + 1, r, idx - (m - l + 1));
}
else
{
return ar[l];
}
}
int main()
{
srand((unsigned int)time(0));
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
cout << quicksort(a, 0, n - 1, (n + 1) / 2) << endl;
return 0;
}