Median and Mode using Counting Sort | Function that sort input array a [ ] and calculate mode and median using counting sort . ; The output array b [ ] will have sorted array ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . Initialize count array as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each element of input array ; mode is the index with maximum count ; Update count [ ] array with sum ; Sorted output array b [ ] to calculate median ; Median according to odd and even array size respectively . ; Output the result ; Driver Code
< ? php function printModeMedian ( $ a , $ n ) { $ b [ $ n ] = array ( ) ; $ max = max ( $ a ) ; $ t = $ max + 1 ; $ count [ $ t ] = array ( ) ; for ( $ i = 0 ; $ i < $ t ; $ i ++ ) $ count [ $ i ] = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ count [ $ a [ $ i ] ] ++ ; $ mode = 0 ; $ k = $ count [ 0 ] ; for ( $ i = 1 ; $ i < $ t ; $ i ++ ) { if ( $ count [ $ i ] > $ k ) { $ k = $ count [ $ i ] ; $ mode = $ i ; } } for ( $ i = 1 ; $ i < $ t ; $ i ++ ) $ count [ $ i ] = $ count [ $ i ] + $ count [ $ i - 1 ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ b [ $ count [ $ a [ $ i ] ] - 1 ] = $ a [ $ i ] ; $ count [ $ a [ $ i ] ] -- ; } $ median ; if ( $ n % 2 != 0 ) $ median = $ b [ $ n / 2 ] ; else $ median = ( $ b [ ( $ n - 1 ) / 2 ] + $ b [ ( $ n / 2 ) ] ) / 2.0 ; echo " median = " , ▁ $ median , ▁ " " ▁ ; STRNEWLINE TABSYMBOL echo ▁ " mode = " } $ a = array ( 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 ) ; $ n = sizeof ( $ a ) ; printModeMedian ( $ a , $ n ) ; ? >