Skip to content

Instantly share code, notes, and snippets.

@meherhowji
Last active February 4, 2019 09:50
Show Gist options
  • Save meherhowji/f2c55b5d8fd5955ae9588473b8c5c397 to your computer and use it in GitHub Desktop.
Save meherhowji/f2c55b5d8fd5955ae9588473b8c5c397 to your computer and use it in GitHub Desktop.
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