
Sort an Array of 0s, 1s and 2s
My Thought Process (Java DSA) When I came across this problem, it initially looked like a normal sorting problem. But the constraint made me rethink the approach. Problem understanding We are given an array arr[] containing only: 0 s 1 s 2 s The task is to sort the array in ascending order without using any built-in sort function . Initial Thinking Let’s take an example: arr = [ 0 , 1 , 2 , 0 , 1 , 2 ] Expected output: [ 0 , 0 , 1 , 1 , 2 , 2 ] At first, the idea of using a sorting function came to mind. But since it is not allowed, I needed a different approach. Key Observation The array contains only three distinct values: 0 1 2 So instead of general sorting, I can group similar elements together . Approach (Dutch National Flag Algorithm) I used three pointers: low → to place 0 s mid → to traverse the array high → to place 2 s Logic i have been used for this problem If arr[mid] == 0 Swap with low , then increment both low and mid If arr[mid] == 1 Just move mid If arr[mid] == 2 Swap w
Continue reading on Dev.to Beginners
Opens in a new tab




