Visualize

Pattern visualizer

Sort Colors

With only three possible values, you don't need real sorting — you need three growing regions that never require re-examining a cell twice: settled 0s on the left, settled 2s on the right, and an unknown middle that shrinks with every look. The Dutch national flag partition keeps those three regions growing at once: 0s settle left of low, 2s settle right of high, and mid scans the unknown middle. Each look at nums[mid] either files a 0 to the front, a 2 to the back, or leaves a 1 in place — so the array sorts itself in one sweep. Animated on: Sort the array [2, 0, 2, 1, 1, 0] of colors (0 = red, 1 = white, 2 = blue) in place, in a single pass, without a counting sort..

Dutch national flag — three pointers, one pass

time O(n)space O(1)step 1 / 10
2
[0]
0
[1]
2
[2]
1
[3]
1
[4]
0
[5]
line 2

Setup: low = 0 (0s will live left of it), high = 5 (2s will live right of it), mid = 0 scans the unknown zone. Everything between low and high is unsorted.

Pseudocode
1FUNCTION sortColors(nums):
2 low = 0, mid = 0, high = (the length of nums) - 1
3 WHILE mid <= high:
4 IF nums[mid] equals 0:
5 swap nums[mid] and nums[low]; move low right; move mid right
6 ELSE IF nums[mid] equals 1:
7 move mid one step right
8 ELSE: (nums[mid] equals 2)
9 swap nums[mid] and nums[high]; move high one step left

← / → step · space play · Home restart

Where to practice Arrays