Median and Mode using Counting Sort | Java Program for Mode and Median using Counting Sort technique ; 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 program
import java . util . Arrays ; class GFG { static void printModeMedian ( int a [ ] , int n ) { int [ ] b = new int [ n ] ; int max = Arrays . stream ( a ) . max ( ) . getAsInt ( ) ; int t = max + 1 ; int count [ ] = new int [ t ] ; for ( int i = 0 ; i < t ; i ++ ) { count [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { count [ a [ i ] ] ++ ; } int mode = 0 ; int k = count [ 0 ] ; for ( int i = 1 ; i < t ; i ++ ) { if ( count [ i ] > k ) { k = count [ i ] ; mode = i ; } } for ( int i = 1 ; i < t ; i ++ ) { count [ i ] = count [ i ] + count [ i - 1 ] ; } for ( int i = 0 ; i < n ; i ++ ) { b [ count [ a [ i ] ] - 1 ] = a [ i ] ; count [ a [ i ] ] -- ; } float median ; if ( n % 2 != 0 ) { median = b [ n / 2 ] ; } else { median = ( float ) ( ( b [ ( n - 1 ) / 2 ] + b [ ( n / 2 ) ] ) / 2.0 ) ; } System . out . println ( " median ▁ = ▁ " + median ) ; System . out . println ( " mode ▁ = ▁ " + mode ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 } ; int n = a . length ; printModeMedian ( a , n ) ; } }