Majority Element | Function to find Majority element in an array it returns - 1 if there is no majority element ; Sort the array in O ( nlogn ) ; Increases the count if the same element occurs otherwise starts counting new element ; Sets maximum count and stores maximum occured element so far if maximum count becomes greater than n / 2 it breaks out setting the flag ; Returns maximum occured element if there is no such element , returns - 1 ; Driver code ; Function calling
function majorityElement ( arr , n ) { arr . sort ( function ( a , b ) { return a - b } ) ; let count = 1 , max_ele = - 1 , temp = arr [ 0 ] , ele = 0 , f = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( temp == arr [ i ] ) { count ++ ; } else { count = 1 ; temp = arr [ i ] ; } if ( max_ele < count ) { max_ele = count ; ele = arr [ i ] ; if ( max_ele > parseInt ( n / 2 , 10 ) ) { f = 1 ; break ; } } } return ( f == 1 ? ele : - 1 ) ; } let arr = [ 1 , 1 , 2 , 1 , 3 , 5 , 1 ] ; let n = 7 ; document . write ( majorityElement ( arr , n ) ) ;