Check for Majority Element in a sorted array | PHP Program to check for majority element in a sorted array function returns 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
< ? php function isMajority ( $ arr , $ n , $ x ) { $ i ; $ last_index = $ n % 2 ? ( $ n / 2 + 1 ) : ( $ n / 2 ) ; for ( $ i = 0 ; $ i < $ last_index ; $ i ++ ) { if ( $ arr [ $ i ] == $ x && $ arr [ $ i + $ n / 2 ] == $ x ) return 1 ; } return 0 ; } $ arr = array ( 1 , 2 , 3 , 4 , 4 , 4 , 4 ) ; $ n = sizeof ( $ arr ) ; $ x = 4 ; if ( isMajority ( $ arr , $ n , $ x ) ) echo $ x , " ▁ appears ▁ more ▁ than ▁ " , floor ( $ n / 2 ) , " ▁ times ▁ in ▁ arr [ ] " ; else echo $ x , " does ▁ not ▁ appear ▁ more ▁ than ▁ " , floor ( $ n / 2 ) , " times ▁ in ▁ arr [ ] " ; ? >