Created
December 19, 2015 23:07
-
-
Save jinwolf/ff8ff2c2f0c58e266ac4 to your computer and use it in GitHub Desktop.
Search a number in an array using Binary Search iteratively (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
| var numList = [1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
| var NOT_FOUND = -1; | |
| var NOT_SORTED = -2; | |
| function search(list, num) { | |
| var start = 0; | |
| var end = list.length - 1; | |
| while (true) { | |
| if (start === end && list[start] !== num) { | |
| return NOT_FOUND; | |
| } | |
| if (list[start] > list[end]) { | |
| // array is not sorted | |
| returh NOT_SORTED; | |
| } | |
| var center = Math.floor((start + end) / 2); | |
| if (list[center] === num) { | |
| return center; | |
| } else if (num < list[center]) { | |
| end = center - 1; | |
| } else { | |
| start = center + 1; | |
| } | |
| } | |
| } | |
| console.log(search(numList, 3)); | |
| console.log(search(numList, 9)); | |
| console.log(search(numList, 12)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment