
Sort 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 How It Works: This method works by using three pointers to keep track of where each type of element should go. The low pointer marks the position where the next 0 should be placed, the mid pointer is use
Continue reading on Dev.to
Opens in a new tab

