-
Notifications
You must be signed in to change notification settings - Fork 1
/
DutchFlag.cpp
61 lines (55 loc) · 1.36 KB
/
DutchFlag.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
// Sort Color Dutch National Flag problem
// Leetcode https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/798/
// https://en.wikipedia.org/wiki/Dutch_national_flag_problem
#include <vector>
#include <iostream>
#include <algorithm>
void print(const std::vector<int>& v)
{
for (auto i : v) {
std::cout << i << " ";
}
}
void sort(std::vector<int>& nums)
{
int end = nums.size() - 1;
int start = 0;
int mid = 0;
while (mid <= end) {
if (nums[mid] < 1) {
std::swap(nums[mid], nums[start]);
start++;
mid++;
} else if (nums[mid] > 1) {
std::swap(nums[mid], nums[end]);
end--;
} else {
mid++;
}
}
}
void test(std::vector<int>& nums)
{
std::cout << "Before sorting : ";
print(nums);
std::cout << "\n";
sort(nums);
std::cout << "After sorting : ";
print(nums);
std::cout << "\n";
std::cout << "============================\n";
}
int main()
{
std::vector<int> nums {2,0,2,1,1,0};
test(nums);
std::vector<int> nums1 {0, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0 };
test(nums1);
std::vector<int> nums2 {};
test(nums2);
std::vector<int> nums3 {1,1,2,1,2,1,2,2,1,2,1};
test(nums3);
std::vector<int> nums4 {0,2,2,0,2};
test(nums4);
return 0;
}