Last active
February 4, 2019 09:50
-
-
Save meherhowji/f2c55b5d8fd5955ae9588473b8c5c397 to your computer and use it in GitHub Desktop.
Iterative Binary Search in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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