Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterative Binary Search in JavaScript
const sortedList = [1,2,3,4,5,6,9,11,12,13,14,15,16,17,18,19,20]
const binarySearch = (list, item) => {
let low = 0
let high = list.length - 1
let guess = null
while(low <= high) {
let mid = Math.floor((high + low)/2)
guess = list[mid]
if(guess === item) {
console.log('The item is present at ' + (mid + 1) + ' position.')
} else if (guess > item) {
high = mid - 1
} else {
low = mid + 1
}
}
}
binarySearch(sortedList, 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.