Majority Element | Function to find Majority element in an array ; sentinels ; update maxCount if count of current element is greater ; if maxCount is greater than n / 2 return the corresponding element ; Driver code ; Function calling
def findMajority ( arr , n ) : NEW_LINE INDENT maxCount = 0 NEW_LINE index = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > maxCount ) : NEW_LINE INDENT maxCount = count NEW_LINE index = i NEW_LINE DEDENT DEDENT if ( maxCount > n // 2 ) : NEW_LINE INDENT print ( arr [ index ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ Majority ▁ Element " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE DEDENT