Created
January 24, 2019 01:36
-
-
Save jharris-code/6c1c3edd51f4b57c2c9ff8c8ca9a78e7 to your computer and use it in GitHub Desktop.
Binary Search
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
| function binarySearch(nums, target) { | |
| let start = 0; | |
| let end = nums.length - 1; | |
| let p; | |
| while(start <= end) { | |
| p = Math.floor((start + end) / 2); | |
| if(nums[p] === target) { | |
| return p; | |
| } else { | |
| if(target < nums[p]){ | |
| end = p - 1; | |
| } else if (target > nums[p]) { | |
| start = p + 1; | |
| } | |
| } | |
| } | |
| return -1; | |
| } | |
| //outputs: 6 | |
| console.log(binarySearch([0,1,3,4,5,6,7,8], 7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment