What is Sort Colors
The array contains only 0, 1, and 2. Group them in that order in one pass. low is the next slot for a 0, high is the next slot for a 2, and mid scans the unknown middle.
2 0 2 1 1 0 0 0 1 1 2 2
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is swapped at most once into a finished side. |
| Memory | O(1) | Three indices and the same array. |
Implementation
def sort_colors(a):
low = mid = 0
high = len(a) - 1
while mid <= high:
if a[mid] == 0:
a[low], a[mid] = a[mid], a[low]
low += 1
mid += 1
elif a[mid] == 2:
a[mid], a[high] = a[high], a[mid]
high -= 1
else:
mid += 1
return a