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
function ceilSearch ( arr , low , high , x ) { let 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 ) ; } } let arr = [ 1 , 2 , 8 , 10 , 10 , 12 , 19 ] ; let n = arr . length ; let x = 20 ; let index = ceilSearch ( arr , 0 , n - 1 , x ) ; if ( index == - 1 ) { document . write ( ` ${ x } ` ) ; } else { document . write ( ` ${ x } ${ arr [ index ] } ` ) ; }