You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
2
-
3
-
// We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
4
-
5
-
// You must solve this problem without using the library's sort function.
6
-
7
-
//The solution of the above problem is
8
1
#include<bits/stdc++.h>
9
2
usingnamespacestd;
10
3
@@ -15,34 +8,39 @@ class Solution {
15
8
int mid = 0; // Pointer for current element being evaluated
16
9
int low = 0; // Pointer for the next position of 0
17
10
int high = nums.size() - 1; // Pointer for the next position of 2
18
-
int temp; // Temporary variable for swapping
19
11
20
12
// Loop until mid pointer surpasses high pointer
21
13
while (high >= mid) {
22
-
// If the current element is 0
23
14
if (nums[mid] == 0) {
24
-
// Swap it with the element at low pointer
25
-
temp = nums[low];
26
-
nums[low] = nums[mid];
27
-
nums[mid] = temp;
28
-
low++; // Move the low pointer forward
29
-
mid++; // Move the mid pointer forward
15
+
swap(nums[low], nums[mid]); // Swap with low pointer
16
+
low++;
17
+
mid++;
30
18
}
31
-
// If the current element is 1
32
19
elseif (nums[mid] == 1) {
33
-
mid++; // Just move the mid pointer forward
20
+
mid++; // Just move mid pointer forward
34
21
}
35
-
// If the current element is 2
36
-
elseif (nums[mid] == 2) {
37
-
// Swap it with the element at high pointer
38
-
temp = nums[high];
39
-
nums[high] = nums[mid];
40
-
nums[mid] = temp;
41
-
high--; // Move the high pointer backward
22
+
else {
23
+
swap(nums[mid], nums[high]); // Swap with high pointer
24
+
high--;
42
25
}
43
26
}
44
27
}
45
28
};
46
-
//This algorithm is known as the DNF or the DUtch National Flag algorithm
47
29
48
-
30
+
intmain() {
31
+
Solution solution;
32
+
33
+
// Example array of 0s, 1s, and 2s (red, white, and blue)
0 commit comments