text: Counting Sort | PHP Program for counting sort ; The main function that sort the given string arr [ ] in alphabatical order ; The output character array that will have sorted arr ; Create a count array to store count of inidividul characters and initialize count array as 0 ; Store count of each character ; Change count [ i ] so that count [ i ] now contains actual position of this character in output array ; Build the output character array To make it stable we are operating in reverse order . ; Copy the output array to arr , so that arr now contains sorted characters ; Driver Code
code: < ? php $ RANGE = 255 ; function countSort ( $ arr ) { global $ RANGE ; $ output = array ( strlen ( $ arr ) ) ; $ len = strlen ( $ arr ) ; $ count = array_fill ( 0 , $ RANGE + 1 , 0 ) ; for ( $ i = 0 ; $ i < $ len ; ++ $ i ) ++ $ count [ ord ( $ arr [ $ i ] ) ] ; for ( $ i = 1 ; $ i <= $ RANGE ; ++ $ i ) $ count [ $ i ] += $ count [ $ i - 1 ] ; for ( $ i = $ len - 1 ; $ i >= 0 ; $ i -- ) { $ output [ $ count [ ord ( $ arr [ $ i ] ) ] - 1 ] = $ arr [ $ i ] ; -- $ count [ ord ( $ arr [ $ i ] ) ] ; } for ( $ i = 0 ; $ i < $ len ; ++ $ i ) $ arr [ $ i ] = $ output [ $ i ] ; return $ arr ; } $ arr = " geeksforgeeks " ; $ arr = countSort ( $ arr ) ; echo " Sorted ▁ character ▁ array ▁ is ▁ " . $ arr ; ? >