-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
dutch_national_flag.cc
81 lines (70 loc) · 2.35 KB
/
dutch_national_flag.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
71
72
73
74
75
76
77
78
79
80
81
#include <algorithm>
#include <array>
#include <vector>
#include "test_framework/generic_test.h"
#include "test_framework/test_failure.h"
#include "test_framework/timed_executor.h"
using std::swap;
using std::vector;
enum class Color { kRed, kWhite, kBlue };
void DutchFlagPartition(int pivot_index, vector<Color>* A_ptr) {
vector<Color>& A = *A_ptr;
Color pivot = A[pivot_index];
/**
* Keep the following invariants during partitioning:
* bottom group: A[0, smaller - 1].
* middle group: A[smaller, equal - 1].
* unclassified group: A[equal, larger - 1].
* top group: A[larger, size(A) - 1].
*/
int smaller = 0, equal = 0, larger = size(A);
// Keep iterating as long as there is an unclassified element.
while (equal < larger) {
// A[equal] is the incoming unclassified element.
if (A[equal] < pivot) {
swap(A[smaller++], A[equal++]);
} else if (A[equal] == pivot) {
++equal;
} else { // A[equal] > pivot.
swap(A[equal], A[--larger]);
}
}
}
void DutchFlagPartitionWrapper(TimedExecutor& executor, const vector<int>& A,
int pivot_idx) {
vector<Color> colors;
colors.resize(A.size());
std::array<int, 3> count = {0, 0, 0};
for (size_t i = 0; i < A.size(); i++) {
count[A[i]]++;
colors[i] = static_cast<Color>(A[i]);
}
Color pivot = colors[pivot_idx];
executor.Run([&] { DutchFlagPartition(pivot_idx, &colors); });
int i = 0;
while (i < colors.size() && colors[i] < pivot) {
count[static_cast<int>(colors[i])]--;
++i;
}
while (i < colors.size() && colors[i] == pivot) {
count[static_cast<int>(colors[i])]--;
++i;
}
while (i < colors.size() && colors[i] > pivot) {
count[static_cast<int>(colors[i])]--;
++i;
}
if (i != colors.size()) {
throw TestFailure("Not partitioned after " + std::to_string(i) +
"th element");
} else if (count != std::array<int, 3>{0, 0, 0}) {
throw TestFailure("Some elements are missing from original array");
}
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"executor", "A", "pivot_idx"};
return GenericTestMain(args, "dutch_national_flag.cc",
"dutch_national_flag.tsv", &DutchFlagPartitionWrapper,
DefaultComparator{}, param_names);
}