-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathQuick.h
57 lines (46 loc) · 1.29 KB
/
Quick.h
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
#ifndef ALGS4_QUICK_H
#define ALGS4_QUICK_H
#include <algorithm>
#include <random>
#include "Sorting.h"
class Quick : public Sorting {
private:
template<typename T>
static int partition(std::vector<T> &a, int lo, int hi);
template<typename T>
static void sort(std::vector<T> &a, int lo, int hi);
public:
template<typename T>
static void sort(std::vector<T> &a);
};
template<typename T>
int Quick::partition(std::vector<T> &a, int lo, int hi) {
int i = lo, j = hi + 1;
T v = a[lo];
// Scan right, scan left, check for scan complete, and exchange.
while (true) {
while (less(a[++i], v)) {
if (i == hi) break;
}
while (less(v, a[--j])) {
if (j == lo) break;
}
if (i >= j) break;
exch(a, i, j);
}
exch(a, lo, j); // Put v = a[j] into position
return j; // with a[lo..j-1] <= a[j] <= a[j+1..hi].
}
template<typename T>
void Quick::sort(std::vector<T> &a, int lo, int hi) {
if (lo >= hi) return;
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
template<typename T>
void Quick::sort(std::vector<T> &a) {
std::shuffle(a.begin(), a.end(), std::default_random_engine(std::random_device()()));
sort(a, 0, a.size() - 1);
}
#endif //ALGS4_QUICK_H