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 first element , then return the first element ; Otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ i + 1 ] , then return arr [ i + 1 ] ; If we reach here then x is greater than the last element of the array , return - 1 in this case ; Driver program to check above functions
def ceilSearch ( arr , low , high , x ) : NEW_LINE INDENT if x <= arr [ low ] : NEW_LINE INDENT return low NEW_LINE DEDENT i = low NEW_LINE for i in range ( high ) : NEW_LINE INDENT if arr [ i ] == x : NEW_LINE INDENT return i NEW_LINE DEDENT if arr [ i ] < x and arr [ i + 1 ] >= x : NEW_LINE INDENT return i + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 1 , 2 , 8 , 10 , 10 , 12 , 19 ] NEW_LINE n = len ( arr ) NEW_LINE x = 3 NEW_LINE index = ceilSearch ( arr , 0 , n - 1 , x ) ; NEW_LINE if index == - 1 : NEW_LINE INDENT print ( " Ceiling ▁ of ▁ % d ▁ doesn ' t ▁ exist ▁ in ▁ array ▁ " % x ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ceiling ▁ of ▁ % d ▁ is ▁ % d " % ( x , arr [ index ] ) ) NEW_LINE DEDENT