Understanding the Problem
We are given an array that only contains the numbers 0, 1, and 2. Our goal is to sort this array in-place so that all 0s come first, followed by all 1s, and then all 2s. This problem is also known as the Dutch National Flag problem.
Since we know the array only has 0s, 1s, and 2s, we can solve this more efficiently than using general sorting algorithms like quicksort. We’ll walk through this step-by-step using an intuitive approach designed for beginners.
Step-by-Step Approach with Example
Let’s say the input array is:
[2, 0, 2, 1, 1, 0]
We will use a three-pointer technique:
low
: Points to the position where the next 0 should go.
mid
: Points to the current element we are checking.
high
: Points to the position where the next 2 should go.
Initial State
low = 0, mid = 0, high = 5
Array: [2, 0, 2, 1, 1, 0]
Case 1: arr[mid] == 0
This value should go to the beginning. We swap arr[mid]
with arr[low]
and move both low
and mid
one step forward.
Case 2: arr[mid] == 1
1 is already in the middle section where it belongs, so we just move mid
forward.
Case 3: arr[mid] == 2
We want to move 2 to the end. We swap arr[mid]
with arr[high]
and move high
backward. But we do not move mid
yet, because we need to check the new element that was swapped in.
Full Walkthrough of the Example
Let’s see how the array evolves:
- Start: [2, 0, 2, 1, 1, 0]
- Swap arr[0] and arr[5] → [0, 0, 2, 1, 1, 2], low = 0, mid = 0, high = 4
- arr[0] == 0 → swap arr[0] and arr[0], move low and mid → [0, 0, 2, 1, 1, 2]
- arr[1] == 0 → swap arr[1] and arr[1], move low and mid → [0, 0, 2, 1, 1, 2]
- arr[2] == 2 → swap arr[2] and arr[4] → [0, 0, 1, 1, 2, 2], high = 3
- arr[2] == 1 → just move mid → [0, 0, 1, 1, 2, 2]
- arr[3] == 1 → just move mid → done
Final result: [0, 0, 1, 1, 2, 2]
Handling Edge Cases
- Empty array: No elements to process — the loop doesn’t run, so we return the array as-is.
- Single element: One value is already "sorted" — return it directly.
- All values are the same: For example, all 0s or all 2s — no swaps needed, array remains unchanged.
Why This Algorithm Is Efficient
Because we only go through the array once — and every swap or comparison brings us closer to the goal — this method runs in O(n) time and uses O(1) space.
It’s fast, space-efficient, and easy to implement once the logic is clear!
Comments
Loading comments...