Check for Majority Element in a sorted array | Javascript Program to check for majority element in a sorted array ; Get last index according to n ( even or odd ) ; Search for first occurrence of x in arr [ ] ; Check if x is present and is present more than n / 2 times ; Driver code
function isMajority ( arr , n , x ) { let i , last_index = 0 ; last_index = ( n % 2 == 0 ) ? parseInt ( n / 2 , 10 ) : parseInt ( n / 2 , 10 ) + 1 ; for ( i = 0 ; i < last_index ; i ++ ) { if ( arr [ i ] == x && arr [ i + parseInt ( n / 2 , 10 ) ] == x ) return true ; } return false ; } let arr = [ 1 , 2 , 3 , 4 , 4 , 4 , 4 ] ; let n = arr . length ; let x = 4 ; if ( isMajority ( arr , n , x ) == true ) document . write ( x + " " + parseInt ( n / 2 , 10 ) + " " ) ; else document . write ( x + " " + parseInt ( n / 2 , 10 ) + " " ) ;