Mode | C ++ Program for Mode 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 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMode ( int a [ ] , int n ) { int b [ n ] ; int max = * max_element ( a , a + n ) ; int t = max + 1 ; int count [ 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 ; } } cout << " mode ▁ = ▁ " << mode ; } int main ( ) { int a [ ] = { 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printMode ( a , n ) ; return 0 ; }