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 ...

Source: DEV Community
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 ```python id="m8q1zd" 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 +=