Sort an array of 0 s , 1 s and 2 s | UTILITY FUNCTIONS ; Sort the input array , the array is assumed to have values in { 0 , 1 , 2 } ; Utility function to print array arr [ ] ; Driver Code
< ? php function swap ( & $ a , & $ b ) { $ temp = $ a ; $ a = $ b ; $ b = $ temp ; } function sort012 ( & $ a , $ arr_size ) { $ lo = 0 ; $ hi = $ arr_size - 1 ; $ mid = 0 ; while ( $ mid <= $ hi ) { switch ( $ a [ $ mid ] ) { case 0 : swap ( $ a [ $ lo ++ ] , $ a [ $ mid ++ ] ) ; break ; case 1 : $ mid ++ ; break ; case 2 : swap ( $ a [ $ mid ] , $ a [ $ hi -- ] ) ; break ; } } } function printArray ( & $ arr , $ arr_size ) { for ( $ i = 0 ; $ i < $ arr_size ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ arr = array ( 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ) ; $ arr_size = sizeof ( $ arr ) ; sort012 ( $ arr , $ arr_size ) ; echo " array ▁ after ▁ segregation ▁ " ; printArray ( $ arr , $ arr_size ) ; ? >