The task is to sort an array that contains only 0s, 1s, and 2s — in that specific order. Instead of using a general-purpose sorting algorithm (like quicksort or mergesort), we use an optimized strategy known as the Dutch National Flag algorithm.
Why This Is Special
We don’t need to compare numbers in a traditional way because we already know the exact values we’re dealing with: just 0, 1, and 2. So, we can design a solution that finishes in one pass and doesn’t need extra space.
Understanding the Three-Pointer Approach
We use three pointers:
low
→ to track where the next 0 should go
mid
→ current index being checked
high
→ to track where the next 2 should go
We start with all three pointers at their respective ends and move mid
through the array.
Case 1: Element is 0
This means we want to bring it to the front. So, we swap arr[mid]
with arr[low]
. Then we move both low
and mid
one step ahead.
Case 2: Element is 1
This is already in the middle section, so we do nothing — just move mid
forward.
Case 3: Element is 2
We want to push this to the end. So, we swap arr[mid]
with arr[high]
, and only move high
backward. We do not move mid
because the element swapped in from the end hasn’t been checked yet.
Handling Edge Cases
- Empty array: The loop never runs, so we return the array as is.
- All elements are the same: Like all 0s or all 2s – array is already sorted, nothing changes.
- Single element: One item is always sorted by itself.
This algorithm ensures that we cover every case and do it efficiently in O(n) time and O(1) space.