What is the best way to sort an array of 0s and 1s ?
Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s and all 2s in last.
Example
[pastacode lang=”cpp” manual=”Input%20%3A%20%20%7B0%2C%201%2C%202%2C%200%2C%201%2C%202%7D%0AOutput%20%3A%20%7B0%2C%200%2C%201%2C%201%2C%202%2C%202%7D%0AInput%20%3A%20%20%7B0%2C%201%2C%201%2C%200%2C%201%2C%202%2C%201%2C%202%2C%200%2C%200%2C%200%2C%201%7D%0AOutput%20%3A%20%7B0%2C%200%2C%200%2C%200%2C%200%2C%201%2C%201%2C%201%2C%201%2C%201%2C%202%2C%202%7D” message=”” highlight=”” provider=”manual”/]
Sample code in C++
[pastacode lang=”cpp” manual=”%23include%20%3Cbits%2Fstdc%2B%2B.h%3E%0Ausing%20namespace%20std%3B%20%0A%20%20%0A%2F%2F%20Function%20to%20segregate%200s%20and%201s%20%0Avoid%20segregate0and1(intarr%5B%5D%2C%20int%20n)%20%0A%7B%20%0A%20%20%20%20int%20count%20%3D%200%3B%20%2F%2F%20Counts%20the%20no%20of%20zeros%20in%20arr%0A%20%20%09%0A%20%20%20%20for%20(inti%20%3D%200%3B%20i%3C%20n%3B%20i%2B%2B)%20%7B%20%0A%20%20%20%20%20%20%20%20if%20(arr%5Bi%5D%20%3D%3D%200)%20%0A%20%20%20%20%20%20%20%20%20%20%20%20count%2B%2B%3B%20%0A%20%20%20%20%7D%20%0A%20%20%0A%20%20%20%20%2F%2F%20Loop%20fills%20the%20arr%20with%200%20until%20count%20%0A%20%20%20%20for%20(inti%20%3D%200%3B%20i%3C%20count%3B%20i%2B%2B)%20%0A%20%20%20%20%20%20%20%20arr%5Bi%5D%20%3D%200%3B%20%0A%20%20%0A%20%20%20%20%2F%2F%20Loop%20fills%20remaining%20arr%20space%20with%201%20%0A%20%20%20%20for%20(inti%20%3D%20count%3B%20i%3C%20n%3B%20i%2B%2B)%20%0A%20%20%20%20%20%20%20%20arr%5Bi%5D%20%3D%201%3B%20%0A%7D%20%0A%20%20%0A%2F%2F%20Function%20to%20print%20segregated%20array%20%0Avoid%20print(intarr%5B%5D%2C%20int%20n)%20%0A%7B%20%0A%20%20%20%20cout%3C%3C%20%22Array%20after%20segregation%20is%20%22%3B%20%0A%20%20%0A%20%20%20%20for%20(inti%20%3D%200%3B%20i%3C%20n%3B%20i%2B%2B)%20%0A%20%20%20%20%20%20%20%20cout%3C%3Carr%5Bi%5D%20%3C%3C%20%22%20%22%3B%20%0A%7D%20%0A%20%20%0A%2F%2F%20Driver%20function%20%0Aint%20main()%20%0A%7B%20%0A%20%20%20%20intarr%5B%5D%20%3D%20%7B%200%2C%201%2C%200%2C%201%2C%201%2C%201%20%7D%3B%20%0A%20%20%20%20int%20n%20%3D%20sizeof(arr)%20%2F%20sizeof(arr%5B0%5D)%3B%20%0A%20%20%20%20%20%20%0A%20%20%20%20segregate0and1(arr%2C%20n)%3B%20%0A%20%20%20%20print(arr%2C%20n)%3B%20%0A%20%20%20%20%20%20%0A%20%20%20%20return%200%3B%20%0A%7D%20″ message=”” highlight=”” provider=”manual”/]
Output
[pastacode lang=”cpp” manual=”Array%20after%20segregation%20is%200%200%201%201%201%201″ message=”” highlight=”” provider=”manual”/]