Mode | Java Program for Mode using Counting Sort technique ; 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
import java . util . Arrays ; class GFG { static void printMode ( int [ ] a , 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 ; } } 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 ; printMode ( a , n ) ; } }