Sort an Array of 0s, 1s, and 2s - Optimal Approach

Sort an Array of 0s, 1s, and 2s - Optimal Approach

Visualization

Algorithm Steps

  1. Given an array arr consisting only of 0s, 1s, and 2s.
  2. Initialize three pointers: low = 0, mid = 0, and high = n - 1.
  3. Traverse the array with mid pointer until it exceeds high:
  4. → If arr[mid] == 0, swap arr[low] and arr[mid], increment both low and mid.
  5. → If arr[mid] == 1, just move mid one step ahead.
  6. → If arr[mid] == 2, swap arr[mid] and arr[high], and decrement high.
  7. Continue until the array is sorted.

Sort 0s, 1s, and 2s in Array using Dutch National Flag Algorithm Code

Python
JavaScript
Java
C++
C
def sort_colors(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], arr[high] = arr[high], arr[mid]
            high -= 1
    return arr

# Sample Input
arr = [2, 0, 2, 1, 1, 0]
print("Sorted Array:", sort_colors(arr))