text: Majority Element | C # 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
code: using System ; class GFG { public static int majorityElement ( int [ ] arr , int n ) { Array . 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 ; Console . WriteLine ( majorityElement ( arr , n ) ) ; } }