Discover how a simple three-pointer trick can sort colors faster than you ever imagined!
Why Sort Colors Two Pointer Dutch Flag in DSA Rust?
Imagine you have a box of mixed colored balls: red, white, and blue. You want to arrange them so all reds come first, then whites, then blues. Doing this by picking each ball and checking where to put it manually is tiring and confusing.
Manually sorting means checking each ball multiple times and moving them around again and again. This takes a lot of time and mistakes happen easily, like mixing colors or missing some balls.
The two-pointer Dutch Flag method uses three pointers to sort the balls in just one pass. It smartly swaps balls to their correct place without extra space or repeated checks, making sorting fast and simple.
for i in 0..colors.len() { for j in i+1..colors.len() { if colors[j] < colors[i] { colors.swap(i, j); } } }
let mut low = 0; let mut mid = 0; let mut high = colors.len() - 1; while mid <= high { match colors[mid] { 0 => { colors.swap(low, mid); low += 1; mid += 1; }, 1 => { mid += 1; }, 2 => { colors.swap(mid, high); if high == 0 { break; } else { high -= 1; } }, _ => {} } }
This method lets you sort three groups quickly in one pass, saving time and effort in many real-world sorting tasks.
Sorting balls by color in a game, organizing files by priority, or grouping items by category in a warehouse can all use this fast sorting trick.
Manual sorting is slow and error-prone.
Two-pointer Dutch Flag sorts in one pass with swaps.
It is efficient and easy to implement for three groups.
Practice
Sort Colors Two Pointer Dutch Flag algorithm?Solution
Step 1: Understand the problem context
The algorithm is designed specifically for arrays with only three distinct values: 0, 1, and 2.Step 2: Identify the sorting goal
The goal is to rearrange the array so that all 0s come first, then all 1s, and finally all 2s, in one pass without extra space.Final Answer:
To sort an array containing only 0s, 1s, and 2s in a single pass -> Option AQuick Check:
Sort Colors = Sort 0,1,2 in one pass [OK]
- Thinking it sorts any integer array
- Confusing it with general sorting algorithms
- Assuming it reverses the array
Solution
Step 1: Identify pointer initialization
In the Dutch Flag algorithm,lowandmidstart at 0, andhighstarts at the last index (len() - 1).Step 2: Check mutability and bounds
All pointers must be mutable to move during sorting, andhighmust belen() - 1to avoid out-of-bounds errors.Final Answer:
let mut low = 0; let mut mid = 0; let mut high = nums.len() - 1; -> Option AQuick Check:
Correct pointer setup = let mut low = 0; let mut mid = 0; let mut high = nums.len() - 1; [OK]
- Setting high to nums.len() causing out-of-bounds
- Not using mutable variables
- Starting pointers at wrong indices
let mut nums = vec![2, 0, 2, 1, 1, 0];
let mut low = 0;
let mut mid = 0;
let mut high = nums.len() - 1;
while mid <= high {
match nums[mid] {
0 => {
nums.swap(low, mid);
low += 1;
mid += 1;
},
1 => {
mid += 1;
},
2 => {
nums.swap(mid, high);
if high == 0 { break; }
high -= 1;
},
_ => {}
}
}
println!("{:?}", nums);Solution
Step 1: Trace initial swaps and pointer moves
Starting with nums = [2,0,2,1,1,0], the algorithm swaps 2 at mid with 0 at high, then moves pointers accordingly.Step 2: Continue until mid passes high
After all swaps and increments, the array becomes sorted as [0, 0, 1, 1, 2, 2].Final Answer:
[0, 0, 1, 1, 2, 2] -> Option CQuick Check:
Sorted 0,1,2 array = [0,0,1,1,2,2] [OK]
- Not updating pointers correctly after swap
- Swapping with wrong indices
- Stopping loop too early
let mut nums = vec![2, 0, 1];
let mut low = 0;
let mut mid = 0;
let mut high = nums.len();
while mid <= high {
match nums[mid] {
0 => {
nums.swap(low, mid);
low += 1;
mid += 1;
},
1 => {
mid += 1;
},
2 => {
nums.swap(mid, high);
high -= 1;
},
_ => {}
}
}Solution
Step 1: Check pointer initialization
high is set to nums.len(), which is one past the last valid index, causing out-of-bounds when accessing nums[high].Step 2: Understand valid index range
Valid indices are 0 to nums.len() - 1, so high should be initialized to nums.len() - 1.Final Answer:
high is initialized to nums.len(), causing out-of-bounds access -> Option DQuick Check:
high must be last index, not length [OK]
- Using length instead of last index for high
- Not incrementing mid after swapping 2
- Ignoring pointer bounds
nums = [1, 2, 0, 1, 2, 0, 1], how many swaps will the Dutch Flag algorithm perform to sort it?Solution
Step 1: Trace swaps during sorting
Initial array: [1, 2, 0, 1, 2, 0, 1]. Swaps occur when 0 or 2 is found at mid.Step 2: Count swaps step-by-step
Swaps: - Swap 0 at index 2 with 1 at low (index 0) -> 1 swap - Swap 2 at index 1 with 1 at high (index 6) -> 1 swap - Swap 0 at index 5 with 1 at low (index 1) -> 1 swap - Swap 2 at index 1 with 1 at high (index 5) -> 1 swap Total swaps = 4.Final Answer:
4 -> Option BQuick Check:
Count swaps for 0 and 2 moves = 4 [OK]
- Counting pointer moves as swaps
- Missing swaps when 2 is swapped
- Assuming swaps equal array length
Ready to prove it?
Pass the test and this pattern moves unknown
