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
< ? php function binarySearch ( $ arr , $ x ) { $ l = 0 ; $ r = count ( $ arr ) ; while ( $ l <= $ r ) { $ m = $ l + ( int ) ( ( $ r - $ l ) / 2 ) ; $ res = strcmp ( $ x , $ arr [ $ m ] ) ; if ( $ res == 0 ) return $ m - 1 ; if ( $ res > 0 ) $ l = $ m + 1 ; else $ r = $ m - 1 ; } return -1 ; } $ arr = array ( " contribute " , " geeks " , " ide " , " practice " ) ; $ x = " ide " ; $ result = binarySearch ( $ arr , $ x ) ; if ( $ result == -1 ) print ( " Element ▁ not ▁ present " ) ; else print ( " Element ▁ found ▁ at ▁ index ▁ " . $ result ) ; ? >