Sort 0,1 and 2
May 7, 2022
Problem:
You are given an array of integers which contains only 0,1 and 2. Sort the array so all 0 will be left side and 1 in the middle and 2 will be on the right side.
Algo:
1. Start the left and mid pointer from 0 and right pointer from end of the array2. Run the while loop till mid <= right3. If value at mid is 0 then swap mid value with left pointer and increment left and mid4. If value at mid index is 1 then increment mid value5. If mid value at mid index is 2 the swap the value at mid index with value at right index and decrement the right value
Code:
Complexity:
Time complexity: O(n)
Space complexity: O(1)