Last active
February 7, 2025 19:20
-
-
Save Keireira/7f70e467ad4361cd0069f09a337adba5 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
| const comparatorF = (element, needle) => element - needle | |
| const binarySearch = (list, needle, comparator = comparatorF) => { | |
| if (!needle || !list) return null | |
| let min = 0 | |
| let max = list.length - 1 | |
| while (min <= max) { | |
| const mid = Math.floor(min + (max - min) / 2) | |
| const quess = list[mid] | |
| const compared = comparator(quess, needle) | |
| if (compared === 0) { | |
| return quess | |
| } else if (compared > 0) { | |
| max = mid - 1 | |
| } else { | |
| min = mid + 1 | |
| } | |
| } | |
| return null | |
| } | |
| export default binarySearch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment