Search an element in a reverse sorted array | Function to search if element X is present in reverse sorted array ; Store the first index of the subarray in which X lies ; Store the last index of the subarray in which X lies ; Store the middle index of the subarray ; Check if value at middle index of the subarray equal to X ; Element is found ; If X is smaller than the value at middle index of the subarray ; Search in right half of subarray ; Search in left half of subarray ; If X not found ; Driver Code
def binarySearch ( arr , N , X ) : NEW_LINE INDENT start = 0 NEW_LINE end = N NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 NEW_LINE if ( X == arr [ mid ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( X < arr [ mid ] ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE X = 5 NEW_LINE print ( binarySearch ( arr , N , X ) ) NEW_LINE DEDENT