Sparse Search | Binary Search in an array with blanks ; Modified Part ; Search for both side for a non empty string ; No non - empty string on both sides ; Normal Binary Search ; Driver code
function binarySearch ( arr , low , high , x ) { if ( low > high ) return - 1 ; let mid = Math . floor ( ( low + high ) / 2 ) ; if ( arr [ mid ] == " " ) { let left = mid - 1 ; let right = mid + 1 ; while ( true ) { if ( left < low && right > high ) return - 1 ; if ( left >= low && arr [ left ] != " " ) { mid = left ; break ; } else if ( right <= high && arr [ right ] != " " ) { mid = right ; break ; } left -- ; right ++ ; } } if ( arr [ mid ] == x ) return mid ; else if ( arr [ mid ] > x ) return binarySearch ( arr , low , mid - 1 , x ) ; else return binarySearch ( arr , mid + 1 , high , x ) ; } function sparseSearch ( arr , x , n ) { return binarySearch ( arr , 0 , n - 1 , x ) ; } let arr = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; let x = " " ; let n = x . length ; let index = sparseSearch ( arr , x , n ) ; if ( index != - 1 ) document . write ( x + " " + index ) ; else document . write ( x + " " ) ;