-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick_sort.cc
70 lines (61 loc) · 1.5 KB
/
quick_sort.cc
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
#include "./include/sort.hh"
// Rearanges subarray A[p..r] in place
template <class T>
int partition(std::vector<T>& A, int p, int r) {
int x = A[r], i = p - 1;
for (int j = p; j < r; j++) {
if (A[j] < x) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i + 1], A[r]);
return i + 1;
}
template <class T>
void quick_sort(std::vector<T>& A, int p, int r) {
if (p < r) {
int q = partition(A, p, r);
quick_sort(A, p, q - 1);
quick_sort(A, q + 1, r);
}
}
template<class T>
int partition_hoare(std::vector<T>& A, int p, int r) {
int x = A[p];
i = p - 1;
j = r + 1;
while (true) {
do {
j--;
} while (A[j] <= x);
do {
i++;
} while (A[i >= x]);
if (i < j) std::swap(A[i], A[j]);
else return j;
}
}
template<class T>
void quick_sort_hoare(std::vector<T>& A, int p, int r) {
if (p < r) {
int q = partition_hoare(A, p, r);
quick_sort_hoare(A, p, q - 1);
quick_sort_hoare(A, q + 1, r);
}
}
template<class T>
int partition_random(std::vector<T>& A, int p, int r) {
int i = rand() % (r - p) + p;
std::swap(A[i], A[r]);
return partition(A, p, r);
}
template <class T>
void quick_sort_random(std::vector<T>& A, int p, int r) {
if (p < r) {
int q = partition_random(A, p, r);
quick_sort_random(A, p, q - 1);
quick_sort_random(A, q + 1, r);
}
}
// TODO: implement 3 way quick sort algorithm