Hey @yashkdot_da870b580af21a9d. You are getting wrong answers bcoz after sorting the array you need to print the array. Secondly Your logic is having some deficiencies that’s why a test case like :
5
2
0
2
1
0
is failing. So you can refer to my logic for benchmarking your logic.
For the question the approach to be followed is to define regions of zero, one and two as there are only these three elements in the array. The region 1 will be of zero as it the least among the three then the region for 1 and in the end the third region of 2’s.
Logic
In this question there will be three regions defined for three different elements. A pointer that keeps a track of where the region for 1 starts and a pointer for where the region for 2 starts. Since 2 is to be placed in the end so the region for two starts in the end and the pointer for 2 decreases as we place a new two. If current element is zero then place it with the pointer where 1 starts and increase the pointer by 1 as zero’s region is expanded.
- itr=0, ptr1=0,ptr2=array size -1
- Repeat the steps 3 , 4 and 5for itr<=ptr2
- If array[itr] is 0 then swap element at ptr1 with itr and increase ptr1 and itr
- If array[itr] is 1 then just increase the itr
- Else the element is 2 , so swap the element at itr and ptr2 and decrease ptr by 1 Time Complexity:- The time complexity of this array is O(n) or linear time complexity. This is an in-place linear algorithm to sort elements.