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
def printModeMedian ( a , n ) : NEW_LINE INDENT b = [ 0 ] * n NEW_LINE Max = max ( a ) NEW_LINE t = Max + 1 NEW_LINE count = [ 0 ] * t NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT mode = 0 NEW_LINE k = count [ 0 ] NEW_LINE for i in range ( 1 , t ) : NEW_LINE INDENT if ( count [ i ] > k ) : NEW_LINE INDENT k = count [ i ] NEW_LINE mode = i NEW_LINE DEDENT DEDENT for i in range ( 1 , t ) : NEW_LINE INDENT count [ i ] = count [ i ] + count [ i - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT b [ count [ a [ i ] ] - 1 ] = a [ i ] NEW_LINE count [ a [ i ] ] -= 1 NEW_LINE DEDENT median = 0.0 NEW_LINE if ( n % 2 != 0 ) : NEW_LINE INDENT median = b [ n // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT median = ( ( b [ ( n - 1 ) // 2 ] + b [ n // 2 ] ) / 2.0 ) NEW_LINE DEDENT print ( " median ▁ = " , median ) NEW_LINE print ( " mode ▁ = " , mode ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printModeMedian ( arr , n ) NEW_LINE DEDENT