Search in an array of strings where non | Compare two string equals are not ; Main function to find string location ; Move mid to the middle ; If mid is empty , find closest non - empty string ; If mid is empty , search in both sides of mid and find the closest non - empty string , and set mid accordingly . ; If str is found at mid ; If str is greater than mid ; If str is smaller than mid ; Input arr of Strings . ; input Search String
function compareStrings ( str1 , str2 ) { let i = 0 ; while ( i < str1 . length - 1 && str1 [ i ] == str2 [ i ] ) i ++ ; if ( str1 [ i ] > str2 [ i ] ) return - 1 ; if ( str1 [ i ] < str2 [ i ] ) return 1 ; else return 0 ; } function searchStr ( arr , str , first , last ) { if ( first > last ) return - 1 ; let mid = parseInt ( ( last + first ) / 2 , 10 ) ; if ( arr [ mid ] == " " ) { let left = mid - 1 ; let right = mid + 1 ; while ( true ) { if ( left < right && right > last ) return - 1 ; if ( right <= last && arr [ right ] != " " ) { mid = right ; break ; } if ( left >= right && ! arr [ left ] == " " ) { mid = left ; break ; } right ++ ; left -- ; } } if ( compareStrings ( str , arr [ mid ] ) == 0 ) return mid ; if ( compareStrings ( str , arr [ mid ] ) < 0 ) return searchStr ( arr , str , mid + 1 , last ) ; return searchStr ( arr , str , first , mid - 1 ) ; } let arr = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; let str = " " ; let n = arr . length ; document . write ( searchStr ( arr , str , 0 , n - 1 ) ) ;