If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sorting Colors, also known as the Dutch National Flag problem, is a popular array sorting problem. The goal is to sort an array containing only 0s, 1s, and 2s in ascending order without using any sorting algorithms like QuickSort or MergeSort.
Here's the problem statement:
Given an array
nums
containing only 0s, 1s, and 2s, sort the array in-place such that all 0s come before 1s, and all 1s come before 2s.Example:
Input: [2, 0, 2, 1, 1, 0] Output: [0, 0, 1, 1, 2, 2]
To solve this problem, we can use a two-pointer approach, often called the Dutch National Flag algorithm. The two pointers
low
andhigh
will be used to keep track of the position of 0s and 2s, respectively.Algorithm:
- Initialize three pointers:
low
,mid
, andhigh
.low
points to the start of the array,mid
points to the start, andhigh
points to the end of the array.- Traverse the array using the
mid
pointer.- If the element at
mid
is 0, swap it with the element atlow
, and increment bothlow
andmid
.- If the element at
mid
is 1, leave it in its place and just incrementmid
.- If the element at
mid
is 2, swap it with the element athigh
, and decrementhigh
.- Repeat steps 3-6 until
mid
becomes greater thanhigh
.Here's the C++ code to sort the colors (0s, 1s, and 2s) in ascending order:
cppCopy code
#include <iostream> #include <vector> void sortColors(std::vector<int>& nums) { int low = 0; int mid = 0; int high = nums.size() - 1; while (mid <= high) { if (nums[mid] == 0) { std::swap(nums[low], nums[mid]); low++; mid++; } else if (nums[mid] == 1) { mid++; } else { std::swap(nums[mid], nums[high]); high--; } } } int main() { std::vector<int> nums = {2, 0, 2, 1, 1, 0}; std::cout << "Before Sorting: "; for (int num : nums) { std::cout << num << " "; } std::cout << std::endl; sortColors(nums); std::cout << "After Sorting: "; for (int num : nums) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Example Output:
mathematicaCopy code
Before Sorting: 2 0 2 1 1 0 After Sorting: 0 0 1 1 2 2
In this solution, the
sortColors
function performs the sorting in-place using the two-pointer approach. The time complexity of this algorithm is O(n), where n is the number of elements in the array.
I bought this course, it worth it!
Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it
Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website
Quick answers to common questions about our courses, quizzes, and learning platform
SCIAKU Team please upload 1st video of TREE please please please, please