Features:
- Returns the index of the search value if found, otherwise,
undefined
- No array copy
- Iterative
function binarySearch(arr, number) {
let start = 0
let end = arr.length - 1
while (start <= end) {
let midIndex = Math.floor((start + end) / 2)
let midpoint = arr[midIndex]
if (midpoint == number) {
return midIndex
}
else if (number < midpoint) {
end = midIndex - 1
}
else {
start = midIndex + 1
}
}
}
With debugging:
function binarySearch(arr, number) {
let start = 0
let end = arr.length - 1
while (start <= end) {
console.log('arr slice', arr.slice(start, end + 1))
console.log('start', start)
console.log('end', end)
let midIndex = Math.floor((start + end) / 2)
let midpoint = arr[midIndex]
console.log('midIndex', midIndex)
console.log('midpoint', midpoint)
if (midpoint == number) {
return midIndex
}
else if (number < midpoint) {
end = midIndex - 1
}
else {
start = midIndex + 1
}
}
}
Output is the same as the recursive version.