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
def majorityElement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count , max_ele , temp , f = 1 , - 1 , arr [ 0 ] , 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( temp == arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 1 NEW_LINE temp = arr [ i ] NEW_LINE DEDENT if ( max_ele < count ) : NEW_LINE INDENT max_ele = count NEW_LINE ele = arr [ i ] NEW_LINE if ( max_ele > ( n // 2 ) ) : NEW_LINE INDENT f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if f == 1 : NEW_LINE INDENT return ele NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 2 , 1 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( majorityElement ( arr , n ) ) NEW_LINE