-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathith Order Statistic.cpp
More file actions
107 lines (96 loc) · 1.5 KB
/
ith Order Statistic.cpp
File metadata and controls
107 lines (96 loc) · 1.5 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
ith Order Statistic
Time Complexity: O(N)
*/
#include <iostream>
using namespace std;
void swap(int A[], int i, int j)
{
int temp;
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int find_pivot(int A[], int l, int r)
{
//Pivot is the median of three elements
int a = l;
int b;
if((r-l)%2 == 0)
{
b = (r+l)/2 - 1;
}
else
{
b = (r+l)/2;
}
int c = r-1;
if((A[a]>=A[b] && A[a]<=A[c]) || (A[a]<=A[b] && A[a]>=A[c]))
{
return a;
}
else if((A[a]>=A[b] && A[b]>=A[c]) || (A[a]<=A[b] && A[b]<=A[c]))
{
return b;
}
else
{
return c;
}
//Pivot is the first element of the subarray
/*
return l;
*/
//Pivot is the last elemeny of the subarray
/*
return r-1;
*/
}
int quick_sort(int A[], int l, int r, int p)
{
int i,j;
i = l+1;
j = l+1;
for(j; j<r; j++)
{
if(A[j]<A[p])
{
swap(A, i, j);
i++;
}
}
swap(A, i-1, p);
return i-1;
}
int find_ith_order_statistic(int A[], int l, int r, int s)
{
int pivot = find_pivot(A,l,r);
swap(A, l, pivot);
int curr_statistic = quick_sort(A, l, r, l);
if(curr_statistic+1 == s)
{
return A[curr_statistic];
}
else if(curr_statistic+1 < s)
{
find_ith_order_statistic(A, curr_statistic+1, r, s);
}
else
{
find_ith_order_statistic(A, l, curr_statistic+1, s);
}
}
int main()
{
int N;
cin>>N;
int A[N];
for(int i = 0; i<N; i++)
{
cin>>A[i];
}
int s;
cin>>s;
cout<<find_ith_order_statistic(A, 0, N, s)<<endl;
return 0;
}