
Task – Sort an Array of 0s, 1s and 2s (Without Using Built-in Sort)
Problem Statement Given an array arr[] containing only 0s, 1s, and 2s, sort the array in ascending order. You must not use any built-in sorting function. Example 1 Input: arr[] = [0, 1, 2, 0, 1, 2] Output: [0, 0, 1, 1, 2, 2] Explanation: All 0s appear first, followed by 1s, then 2s. 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] Explanation: The elements are rearranged in ascending order. Constraints 1 ≤ arr.size() ≤ 10^5 0 ≤ arr[i] ≤ 2 Approach Since the array contains only three distinct values (0, 1, 2), we can solve this efficiently using three pointers. We maintain: low → position for next 0 mid → current element being checked high → position for next 2 Working Logic If arr[mid] == 0 Swap arr[low] and arr[mid], increment both low and mid If arr[mid] == 1 Just move mid forward If arr[mid] == 2 Swap arr[mid] and arr[high], decrement high This ensures: Left side contains 0s Middle contains 1s Right side contains 2s Time and
Continue reading on Dev.to Beginners
Opens in a new tab



