← Two PointersDSA 1.1.E

Partition (3-way)

Dutch National Flag-style three-region partitioning. Sort Colors.

StatusCollected
Notes1 solved

Three pointers instead of two, splitting the array into three regions in a single pass — the Dutch National Flag problem, solved here as Sort Colors (sorting an array of only 0s, 1s, and 2s in place).

void sortColors(int *nums, int n) {
      int low = 0, mid = 0, high = n - 1;
      while (mid <= high) {
          if (nums[mid] == 0) {
              int tmp = nums[low]; nums[low] = nums[mid]; nums[mid] = tmp;
              low++; mid++;
          } else if (nums[mid] == 1) {
              mid++;
          } else {
              int tmp = nums[mid]; nums[mid] = nums[high]; nums[high] = tmp;
              high--;   /* mid does NOT advance — the swapped-in value is unexamined */
          }
      }
  }

The one detail that actually matters: after swapping with high, mid stays put, because the value swapped in from the high end hasn't been looked at yet. Swapping with low is safe to advance past, since everything below mid is already known to be sorted into place.

Notes from readers

Comments — via GitHub