Binary Search a String | Returns index of x if it is present in arr [ ] , else return - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; Driver Code
def binarySearch ( arr , x ) : NEW_LINE INDENT l = 0 NEW_LINE r = len ( arr ) NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = l + ( ( r - l ) // 2 ) NEW_LINE res = ( x == arr [ m ] ) NEW_LINE if ( res == 0 ) : NEW_LINE INDENT return m - 1 NEW_LINE DEDENT if ( res > 0 ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " contribute " , " geeks " , " ide " , " practice " ] ; NEW_LINE x = " ide " NEW_LINE result = binarySearch ( arr , x ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( " Element ▁ not ▁ present " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element ▁ found ▁ at ▁ index " , result ) NEW_LINE DEDENT DEDENT