Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] ; If x is same as middle element , then return mid ; If x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; If x is smaller than arr [ mid ] , then either arr [ mid ] is ceiling of x or ceiling lies in arr [ low ... . mid - 1 ] ; Driver Code
< ? php function ceilSearch ( $ arr , $ low , $ high , $ x ) { $ mid ; if ( $ x <= $ arr [ $ low ] ) return $ low ; if ( $ x > $ arr [ $ high ] ) return -1 ; $ mid = ( $ low + $ high ) / 2 ; if ( $ arr [ $ mid ] == $ x ) return $ mid ; else if ( $ arr [ $ mid ] < $ x ) { if ( $ mid + 1 <= $ high && $ x <= $ arr [ $ mid + 1 ] ) return $ mid + 1 ; else return ceilSearch ( $ arr , $ mid + 1 , $ high , $ x ) ; } else { if ( $ mid - 1 >= $ low && $ x > $ arr [ $ mid - 1 ] ) return $ mid ; else return ceilSearch ( $ arr , $ low , $ mid - 1 , $ x ) ; } } $ arr = array ( 1 , 2 , 8 , 10 , 10 , 12 , 19 ) ; $ n = sizeof ( $ arr ) ; $ x = 20 ; $ index = ceilSearch ( $ arr , 0 , $ n - 1 , $ x ) ; if ( $ index == -1 ) echo ( " Ceiling ▁ of ▁ $ x ▁ doesn ' t ▁ exist ▁ in ▁ array ▁ " ) ; else echo ( " ceiling ▁ of ▁ $ x ▁ is " ) ; echo ( isset ( $ arr [ $ index ] ) ) ; ? >