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 method to test above
function binarySearch ( arr , x ) { let l = 0 , r = arr . length - 1 ; while ( l <= r ) { let m = l + Math . floor ( ( r - l ) / 2 ) ; let res = x . localeCompare ( arr [ m ] ) ; if ( res == 0 ) return m ; if ( res > 0 ) l = m + 1 ; else r = m - 1 ; } return - 1 ; } let arr = [ " " , " " , " " , " " ] ; let x = " " ; let result = binarySearch ( arr , x ) ; if ( result == - 1 ) document . write ( " " ) ; else document . write ( " " + " " + result + " " ) ;