-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cpp
More file actions
97 lines (59 loc) · 1.21 KB
/
Copy pathQuickSort.cpp
File metadata and controls
97 lines (59 loc) · 1.21 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
#include<bits/stdc++.h>
using namespace std;
class Quicksort {
public:
int partition(vector<int> & a, int low, int high) {
int pivot = a[high];
int i = low - 1;
for(int j = low; j<high; j++) {
if(a[j] < pivot) {
i++;
swap(a[i], a[j]);
}
}
swap(a[i+1], a[high]);
return i+1;
}
void quickSort(vector<int> & arr, int low, int high) {
if(low < high) {
int index = partition(arr, low, high);
quickSort(arr, low, index - 1);
quickSort(arr, index+1, high);
}
return;
}
void quickSelect(vector<int> & a, int low, int high, int k) {
if(low < high) {
int index = partition(a, low, high);
if(a.size() - index >= k) {
quickSelect(a, index+1, high, k);
}
else if(a.size() - index < k) {
quickSelect(a, low, index-1, k);
}
}
}
};
ostream& operator << (ostream& cout, vector<int> & a) {
for(int x : a) {
cout << setw(3) << x << ' ';
}
cout << endl;
return cout;
}
int main() {
vector<int> arr;
int n;
cin >> n;
srand(10+n);
for(int i=0;i<n;i++) {
arr.push_back(rand()%100 + 1);
}
for(int x : arr) {
cout << x << ' ';
}
cout << endl;
Quicksort qs;
qs.quickSelect(arr, 0, arr.size() - 1, 3);
cout << arr << endl;
}