algorithm correctly sorts the two colors by swapping
DSA C
while (mid <= high) {
When to Use This Pattern
When you see a problem asking to sort three distinct values quickly and in place, use the Dutch National Flag two-pointer pattern to separate them efficiently.
Common Mistakes
Mistake: Incrementing mid pointer after swapping with high when nums[mid] == 2 Fix: Do not increment mid after swapping with high because the swapped element needs to be checked
Mistake: Swapping incorrectly between pointers causing infinite loops Fix: Always swap nums[mid] with nums[low] or nums[high] carefully and update pointers accordingly
Summary
Sorts an array of 0s, 1s, and 2s in one pass using two pointers.
Use when you need to sort three distinct values efficiently without extra space.
The key is to maintain three regions with pointers low, mid, and high to separate colors.