Sorting an Array of 0s, 1s, and 2s

In this task, I worked on sorting an array that contains only 0s, 1s, and 2s. Instead of using a normal sorting method, I used a more efficient approach that sorts the array in a single pass.

What I Did

I created a function called sort012 that takes an array of 0s, 1s, and 2s and returns the sorted array.

For example:
Input: [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]

How I Solved It

To solve this, I used three pointers:

  • low → to place 0s
  • mid → to traverse the array
  • high → to place 2s

I started all pointers at the beginning except high, which starts at the end.

Then I used a loop to go through the array:

  • If the element is 0 → swap it with the low position and move both low and mid
  • If the element is 1 → just move mid
  • If the element is 2 → swap it with the high position and move high

Code

def sort012(arr):
low = 0
mid = 0
high = len(arr) – 1

while mid <= high:
    if arr[mid] == 0:
        arr[low], arr[mid] = arr[mid], arr[low]
        low += 1
        mid += 1
    elif arr[mid] == 1:
        mid += 1
    else:  # arr[mid] == 2
        arr[mid], arr[high] = arr[high], arr[mid]
        high -= 1
return arr

print(sort012([0, 1, 2, 0, 1, 2]))
print(sort012([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]))

How It Works

This approach works by dividing the array into three parts:

  • Left side for 0s
  • Middle for 1s
  • Right side for 2s

As the loop runs, elements are moved into their correct positions using swaps. This way, the array gets sorted without needing extra space or multiple passes.