-
Notifications
You must be signed in to change notification settings - Fork 1
/
9.2-3.cpp
73 lines (54 loc) · 912 Bytes
/
9.2-3.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Randomised Select - Recursive
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int A[10000];
int partition(int start, int end){
int temp;
int pivot = A[end];
int i = start;
for(int j=start;j<end;j++){
if(pivot > A[j]){
temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
}
}
temp = A[i];
A[i] = A[end];
A[end] = temp;
return i;
}
int Rselect(int start, int end, int index){
// int p;
if(start<end){
int p = partition(start,end);
if(index==p){
return A[p];
}
else if(index<p){
return Rselect(start,p-1, index);
}
else{
return Rselect(p+1,end, index);
}
}
}
int main(){
int n, k;
cin >> n;
k=n;
srand(time(NULL));
cout << "Numbers:" << endl;
while(k){
A[n-k] = rand() % n+1;
cout << A[n-k] << endl;
k--;
}
int index;
cin >> index;
cout << "Selected Random: " << Rselect(0,n-1,index) << endl;
return 0;
}