This binary search works with numbers, but not working with stings
function binary_search(Array, key) {
var middleIndex = Math.floor(Array.length / 2)
var middleValue = numberArray[middleIndex]
//base case key = middle element
if (middleValue === key) return true
else if (middleValue < key && Array.length > 1) {
return binary_search(Array.splice(middleIndex, Array.length), key)
}
else if (middleValue > key && Array.length > 1) {
return binary_search(Array.splice(0, middleIndex), key)
}
else return false
}
If I give it numbers, it works:
console.log(binary_search([5,7,12,16,36,39,42,56,71], 36))
output: true
But not with strings:
console.log(binary_search(['cat', 'dog', 'bird', 'fish'], 'dog'))
result : flase
I understand the array must be presorted for this to work, but how to do this with strings?
['cat', 'dog', 'bird', 'fish'].sort()splicewill modify your input array !!!