Forem

ARUL SELVI ML
ARUL SELVI ML

Posted on

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

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

Problem Statement

Given an array consisting of only 0s, 1s and 2s, sort the array in ascending order.


Examples

Input
arr = [0, 2, 1, 2, 0]

Output
[0, 0, 1, 2, 2]


Input
arr = [2, 0, 1]

Output
[0, 1, 2]


Approach 1 Using Sorting

The simplest way is to sort the array using built in functions.


Code

```python id="sort1"
def sortArray(arr):
arr.sort()
return arr




---

## Approach 2 Counting Method

Count the number of 0s, 1s and 2s, then overwrite the array.

---

### Steps

1 Count number of 0s, 1s and 2s
2 Fill array with 0s
3 Then fill with 1s
4 Then fill with 2s

---

### Code



```python id="sort2"
def sortArray(arr):
    count0 = arr.count(0)
    count1 = arr.count(1)
    count2 = arr.count(2)

    i = 0

    for _ in range(count0):
        arr[i] = 0
        i += 1

    for _ in range(count1):
        arr[i] = 1
        i += 1

    for _ in range(count2):
        arr[i] = 2
        i += 1

    return arr
Enter fullscreen mode Exit fullscreen mode

Approach 3 Dutch National Flag Algorithm

This is the most efficient method.


Steps

1 Maintain three pointers low, mid and high
2 low is for 0 placement
3 mid is current element
4 high is for 2 placement


Code

```python id="sort3"
def sortArray(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], arr[high] = arr[high], arr[mid]
        high -= 1

return arr
Enter fullscreen mode Exit fullscreen mode



---

## Explanation

The Dutch National Flag method works by dividing the array into three parts. It ensures that all 0s are moved to the beginning, 1s stay in the middle, and 2s move to the end in a single traversal.

---

## Expected Output

Input
arr = [0, 2, 1, 2, 0]

Output
[0, 0, 1, 2, 2]

---

## Conclusion

Sorting 0s, 1s and 2s is a common problem that helps understand array manipulation and pointer techniques. The Dutch National Flag algorithm is widely used because it solves the problem efficiently in one pass.

Practice this problem to strengthen your understanding of arrays and in place operations.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)