Created
April 7, 2025 00:59
-
-
Save paulohfev/2e5a148317f5bcf0a99f44e121c9f6e7 to your computer and use it in GitHub Desktop.
Binary Search Algorithm
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
| // Binary search | |
| const bSearch = (list, number) => { | |
| // low and high keep track of which part of the list you’ll search in. | |
| let low = 0 | |
| let high = list.length - 1 | |
| // While you haven’t narrowed it down to one element … | |
| while (low <= high) { | |
| let mid = Math.floor((low + high) / 2) | |
| // … check the middle element. | |
| let guess = list[mid] | |
| if (guess === number) { // Found the item | |
| return mid | |
| } else if (guess > number) { // The guess was too high | |
| high = mid - 1 | |
| } else { // The guess was too low | |
| low = mid + 1 | |
| } | |
| } | |
| return null | |
| } | |
| console.log(bSearch([1, 3, 5, 7, 9], 9)) | |
| console.log(bSearch([1, 3, 5, 7, 9], 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment