Majority Element | Java program to find Majority element in an array ; 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
import java . io . * ; import java . util . * ; class GFG { public static int majorityElement ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; int count = 1 , max_ele = - 1 , temp = arr [ 0 ] , ele = 0 , f = 0 ; for ( int 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 > ( n / 2 ) ) { f = 1 ; break ; } } } return ( f == 1 ? ele : - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 5 , 1 } ; int n = 7 ; System . out . println ( majorityElement ( arr , n ) ) ; } }