text: Majority Element | Function to find the candidate for Majority ; Function to check if the candidate occurs more than n / 2 times ; Function to print Majority Element ; Find the candidate for Majority ; Print the candidate if it is Majority ; Driver Code ; Function call
code: function findCandidate ( a , size ) { let maj_index = 0 , count = 1 ; let i ; for ( i = 1 ; i < size ; i ++ ) { if ( a [ maj_index ] == a [ i ] ) count ++ ; else count -- ; if ( count == 0 ) { maj_index = i ; count = 1 ; } } return a [ maj_index ] ; } function isMajority ( a , size , cand ) { let i , count = 0 ; for ( i = 0 ; i < size ; i ++ ) { if ( a [ i ] == cand ) count ++ ; } if ( count > parseInt ( size / 2 , 10 ) ) return true ; else return false ; } function printMajority ( a , size ) { let cand = findCandidate ( a , size ) ; if ( isMajority ( a , size , cand ) ) document . write ( " " + cand + " " ) ; else document . write ( " " ) ; } let a = [ 1 , 3 , 3 , 1 , 2 ] ; let size = a . length ; printMajority ( a , size ) ;