-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0075. Sort Colors.cpp
More file actions
38 lines (34 loc) · 915 Bytes
/
0075. Sort Colors.cpp
File metadata and controls
38 lines (34 loc) · 915 Bytes
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
class Solution {
public:
void sortColors(vector<int> &nums) {
// Dijkstra 3-Way Partition AKA Dutch national flag problem
// pointers and value of the pivot
int i = 0, j = 0, k = nums.size() - 1, pivot = 1;
// loop through entire array
while (j <= k) {
// if less than pivot, move to [0, i)
if (nums[j] < pivot) {
swap(nums[i], nums[j]);
i++;
j++;
}
// if greater than pivot, move to [k+1, end]
else if (nums[j] > pivot) {
swap(nums[j], nums[k]);
k--;
}
// if same, move j
else {
j++;
}
}
}
};
/*
invariant: i <= j <= k
ranges:
[0, i) is less than pivot
[i, j) is equal to pivot
[j, k] is unsorted
[k+1, end] is greater than pivot
*/