Skip to content

Commit b2deffd

Browse files
authored
Merge pull request #50 from akshit397a/patch-10
Update Dutch_national_Flag.cpp
2 parents 53bd894 + e64e2bc commit b2deffd

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,3 @@
1-
// 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
81
#include <bits/stdc++.h>
92
using namespace std;
103

@@ -15,34 +8,39 @@ class Solution {
158
int mid = 0; // Pointer for current element being evaluated
169
int low = 0; // Pointer for the next position of 0
1710
int high = nums.size() - 1; // Pointer for the next position of 2
18-
int temp; // Temporary variable for swapping
1911

2012
// Loop until mid pointer surpasses high pointer
2113
while (high >= mid) {
22-
// If the current element is 0
2314
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++;
3018
}
31-
// If the current element is 1
3219
else if (nums[mid] == 1) {
33-
mid++; // Just move the mid pointer forward
20+
mid++; // Just move mid pointer forward
3421
}
35-
// If the current element is 2
36-
else if (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--;
4225
}
4326
}
4427
}
4528
};
46-
//This algorithm is known as the DNF or the DUtch National Flag algorithm
4729

48-
30+
int main() {
31+
Solution solution;
32+
33+
// Example array of 0s, 1s, and 2s (red, white, and blue)
34+
vector<int> nums = {2, 0, 2, 1, 1, 0};
35+
36+
// Call the sortColors function to sort the array
37+
solution.sortColors(nums);
38+
39+
// Output the sorted array
40+
for (int num : nums) {
41+
cout << num << " ";
42+
}
43+
cout << endl;
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)