-
Notifications
You must be signed in to change notification settings - Fork 153
/
quick_select_order_stat_linear.cpp
55 lines (51 loc) · 1.03 KB
/
quick_select_order_stat_linear.cpp
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
/**
* Description: Quick Select (Find Kth order statistics)
* Usage: quick_select O(N)
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
int randomised_partition(vector<int> &A, int p, int q){
int random = (rand() % (q-p+1)) + p;
swap(A[q], A[random]);
int ptr = p;
for (int i = p; i <= q; i++) {
if (A[i] <= A[q]) {
swap(A[i], A[ptr++]);
}
}
return ptr;
}
int quick_select(vector<int> &A, int p, int q, int k){
if (p == q) return A[p];
int pivot = randomised_partition(A, p, q);
if (pivot == k)
return A[pivot];
else if (k < pivot) {
return quick_select(A, p, pivot - 1, k);
} else {
return quick_select(A, pivot + 1, q, k);
}
}
int main(){
srand(time(NULL));
int t;
cin >> t;
while (t--) {
int n;
scanf("%d", &n);
vector<int> A(n);
for (int i = 0; i < n; i++) scanf("%d", &A[i]);
int q;
cin >> q;
while (q--) {
int k;
cin >> k;
cout << quick_select(A, 0, n - 1, k) << endl;
}
}
}