DEV Community

Tharunya K R
Tharunya K R

Posted on

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

Problem

Given an array arr[] containing only 0s, 1s, and 2s, sort the array in ascending order without using the built-in sort function.

Example 1
Input: arr = [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]

Example 2
Input: arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]

Approach

Maintain three pointers:
low → next position for 0
mid → current element
high → next position for 2
Traverse the array with mid pointer:
If arr[mid] == 0, swap with arr[low], increment low and mid.
If arr[mid] == 1, just increment mid.
If arr[mid] == 2, swap with arr[high] and decrement high.
Stop when mid > high.

Python Code

class Solution:
def sort012(self, arr):
low, mid, high = 0, 0, 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
Enter fullscreen mode Exit fullscreen mode

Output
Sorted array: [0, 0, 1, 1, 2, 2]
Sorted array: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]

Top comments (0)