Sort Colors (Dutch Flag)

medium

Sort array of 0s, 1s, 2s in-place using three pointers

Step-by-Step Walkthrough: Sort Colors (Dutch Flag)

Three pointers: low for 0s, mid scans, high for 2s. One pass O(n).

  1. Setup

    low=0 (0s go here), mid=0 (scanner), high=5 (2s go here)

  2. Found 2

    mid=0 sees 2. Swap with high. Decrease high.

  3. Found 0

    mid=0 sees 0. Swap with low. Increase both.

  4. Found 1

    mid sees 1. It's in the right zone. Just move mid.

  5. Done

    mid > high, sorting complete!