Maximum element in a sorted and rotated array | Function to return the maximum element ; This condition is for the case when array is not rotated at all ; Find mid ; Check if mid reaches 0 , it is greater than next element or not ; Check if mid itself is maximum element ; Decide whether we need to go to the left half or the right half ; Driver code
< ? php function findMax ( $ arr , $ low , $ high ) { if ( $ high <= $ low ) return $ arr [ $ low ] ; $ mid = $ low + ( $ high - $ low ) / 2 ; if ( $ mid == 0 && $ arr [ $ mid ] > $ arr [ $ mid - 1 ] ) return $ arr [ 0 ] ; if ( $ mid < $ high && $ arr [ $ mid + 1 ] < $ arr [ $ mid ] && $ mid > 0 && $ arr [ $ mid ] > $ arr [ $ mid - 1 ] ) { return $ arr [ $ mid ] ; } if ( $ arr [ $ low ] > $ arr [ $ mid ] ) { return findMax ( $ arr , $ low , $ mid - 1 ) ; } else { return findMax ( $ arr , $ mid + 1 , $ high ) ; } } $ arr = array ( 5 , 6 , 1 , 2 , 3 , 4 ) ; $ n = sizeof ( $ arr ) ; echo findMax ( $ arr , 0 , $ n - 1 ) ;