Search an element in a sorted and rotated array | Returns index of key in arr [ l . . h ] if key is present , otherwise returns - 1 ; If arr [ l ... mid ] is sorted ; As this subarray is sorted , we can quickly check if key lies in half or other half ; If key not lies in first half subarray , Divide other half into two subarrays , such that we can quickly check if key lies in other half ; If arr [ l . . mid ] is not sorted , then arr [ mid ... r ] must be sorted ; Driver program
def search ( arr , l , h , key ) : NEW_LINE INDENT if l > h : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( l + h ) // 2 NEW_LINE if arr [ mid ] == key : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ l ] <= arr [ mid ] : NEW_LINE INDENT if key >= arr [ l ] and key <= arr [ mid ] : NEW_LINE INDENT return search ( arr , l , mid - 1 , key ) NEW_LINE DEDENT return search ( arr , mid + 1 , h , key ) NEW_LINE DEDENT if key >= arr [ mid ] and key <= arr [ h ] : NEW_LINE INDENT return search ( a , mid + 1 , h , key ) NEW_LINE DEDENT return search ( arr , l , mid - 1 , key ) NEW_LINE DEDENT arr = [ 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 , 3 ] NEW_LINE key = 6 NEW_LINE i = search ( arr , 0 , len ( arr ) - 1 , key ) NEW_LINE if i != - 1 : NEW_LINE INDENT print ( " Index : ▁ % ▁ d " % i ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Key ▁ not ▁ found " ) NEW_LINE DEDENT