Created
October 17, 2017 05:53
-
-
Save neewbee/c7eaad3deb1596a2c9e921a410ab40dd to your computer and use it in GitHub Desktop.
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(arr, target) { | |
| let left = 0; | |
| let right = arr.length - 1; | |
| while (left <= right) { | |
| const mid = left + Math.floor((right - left) / 2); | |
| if (arr[mid] === target) { | |
| return mid; | |
| } | |
| if (arr[mid] < target) { | |
| left = mid + 1; | |
| } else { | |
| right = mid - 1; | |
| } | |
| } | |
| return -1; | |
| } | |
| console.log(binarySearch([1, 2, 3, 10], 1) === 0) | |
| console.log(binarySearch([1, 2, 3, 10], 2) === 1) | |
| console.log(binarySearch([1, 2, 3, 10], 3) === 2) | |
| console.log(binarySearch([1, 2, 3, 10], 10) === 3) | |
| console.log(binarySearch([1, 2, 3, 10], 9) === -1) | |
| console.log(binarySearch([1, 2, 3, 10], 4) === -1) | |
| console.log(binarySearch([1, 2, 3, 10], 0) === -1) | |
| console.log(binarySearch([1, 2, 3, 10], 11) === -1) | |
| console.log(binarySearch([5, 7, 8, 10], 3) === -1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment