How does the Dutch National Flag three-way partitioning algorithm sort 0s, 1s, and 2s in a single pass? | A1LabDavid to DSAEnglish • 17 hours ago

How does the Dutch National Flag three-way partitioning algorithm sort 0s, 1s, and 2s in a single pass?

message-square
0
1
How does the Dutch National Flag three-way partitioning algorithm sort 0s, 1s, and 2s in a single pass?
How does the Dutch National Flag three-way partitioning algorithm sort 0s, 1s, and 2s in a single pass? | A1LabDavid to DSAEnglish • 17 hours ago

Dutch National Flag Problem: 3-Way In-Place Partitioning in a Single Pass

The Dutch National Flag (DNF) Algorithm, designed by Edsger Dijkstra, partitions an array containing only three distinct keys (typically 0, 1, and 2) into sorted order in a single pass ($O(n)$ time) and strictly $O(1)$ auxiliary memory.

A standard counting sort solves this with two passes (one to tally frequencies, another to overwrite). The DNF algorithm does it in one pass by maintaining four contiguous array sections using three boundary pointers.


The Four Partition Zones and Loop Invariants

The algorithm divides the array into four regions using pointers low, mid, and high:

+---------------+---------------+-----------------+---------------+
|      0s       |      1s       |   Unexamined    |      2s       |
+---------------+---------------+-----------------+---------------+
0            low-1 low        mid-1 mid           high high+1     n-1
  • Zone 1 (0 to low - 1): Contains strictly 0s (red).
  • Zone 2 (low to mid - 1): Contains strictly 1s (white).
  • Zone 3 (mid to high): Contains unexamined elements yet to be sorted.
  • Zone 4 (high + 1 to n - 1): Contains strictly 2s (blue).

Termination Condition: The sorting process concludes when mid > high, which shrinks the unexamined zone to zero elements.


Pointer Movement Rules

Initialize: low = 0, mid = 0, high = n - 1.

Inspect nums[mid] at each step:

  1. If nums[mid] == 0:

    • Swap nums[low] and nums[mid].
    • Increment both pointers: low++, mid++.
    • Why increment mid? The value swapped from nums[low] into nums[mid] is guaranteed to be a 1 (or nums[low] and nums[mid] pointed to the exact same index 0), which has already been evaluated.
  2. If nums[mid] == 1:

    • It is already in the correct middle region.
    • Simply advance the scanning pointer: mid++.
  3. If nums[mid] == 2:

    • Swap nums[mid] and nums[high].
    • Decrement the upper bound: high--.
    • Do NOT increment mid: The new element brought into nums[mid] from nums[high] was previously unexamined. It could be a 0, 1, or 2, so it must be evaluated on the very next iteration.

Trace Walkthrough: nums = [2, 0, 2, 1, 1, 0]

  • Start: low = 0, mid = 0, high = 5
Step nums[mid] Action Array After Action New Pointers
0 nums[0] = 2 Swap with high (5), high-- [0, 0, 2, 1, 1, 2] low=0, mid=0, high=4
1 nums[0] = 0 Swap with low (0), low++, mid++ [0, 0, 2, 1, 1, 2] low=1, mid=1, high=4
2 nums[1] = 0 Swap with low (1), low++, mid++ [0, 0, 2, 1, 1, 2] low=2, mid=2, high=4
3 nums[2] = 2 Swap with high (4), high-- [0, 0, 1, 1, 2, 2] low=2, mid=2, high=3
4 nums[2] = 1 Correct zone; advance mid++ [0, 0, 1, 1, 2, 2] low=2, mid=3, high=3
5 nums[3] = 1 Correct zone; advance mid++ [0, 0, 1, 1, 2, 2] low=2, mid=4, high=3
  • mid ($4$) $> \text{high}$ ($3$) $\implies$ Loop terminates with [0, 0, 1, 1, 2, 2].

Implementation (C++ and Python)

C++ Implementation

#include <vector>
#include <algorithm>

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 { // nums[mid] == 2
            std::swap(nums[mid], nums[high]);
            high--;
            // mid is not incremented; re-evaluate the swapped element
        }
    }
}

Python Implementation

def sort_colors(nums: list[int]) -> None:
    """
    Sorts nums containing 0s, 1s, and 2s in-place in a single pass.
    """
    low = 0
    mid = 0
    high = len(nums) - 1

    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:  # nums[mid] == 2
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1
            # Do not increment mid here

Complexity Analysis

Metric Complexity Explanation
Time Complexity $O(n)$ At each step of the while loop, either mid increments or high decrements. The unexamined range $[mid, high]$ decreases in size by at least $1$ per operation. The total number of iterations is strictly bounded by $n$.
Auxiliary Space $O(1)$ Rearrangement is performed strictly in-place with three integer index variables.

Application in Quicksort (3-Way Partitioning)

The primary industrial application of this algorithm is in Bentley-McIlroy 3-way Quicksort (fat pivot partitioning). When an input array contains a significant number of duplicate keys, standard 2-way Lomuto or Hoare partitioning degrades toward $O(n^2)$.

By replacing 2-way partitioning with Dijkstra’s 3-way partition:

  • Left partition: elements $< \text{pivot}$
  • Middle partition: elements $== \text{pivot}$
  • Right partition: elements $> \text{pivot}$

The recursive subproblems completely skip the middle partition, solving arrays with all identical elements in $O(n)$ linear time.