Mode | Function that sort input array a [ ] and calculate mode and median using counting sort . ; 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 ; Driver code
function printMode ( a , n ) { let max = Number . MIN_VALUE ; for ( let i = 0 ; i < a . length ; i ++ ) { max = Math . max ( max , a [ i ] ) ; } let t = max + 1 ; let count = new Array ( t ) ; for ( let i = 0 ; i < t ; i ++ ) count [ i ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; let mode = 0 ; let k = count [ 0 ] ; for ( let i = 1 ; i < t ; i ++ ) { if ( count [ i ] > k ) { k = count [ i ] ; mode = i ; } } document . write ( " " + mode ) ; } let a = [ 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 ] ; let n = a . length ; printMode ( a , n ) ;