Last active
November 17, 2021 17:20
-
-
Save zbicin/6887e370053e28b858cb5a304b822167 to your computer and use it in GitHub Desktop.
Binary Search implementation in 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
| function binarySearch(arr, value, start = 0, end = arr.length - 1) { | |
| if (start > end) { | |
| return -1; | |
| } | |
| const middleElementIndex = Math.floor((end - start) / 2) + start; | |
| const middleElementValue = arr[middleElementIndex]; | |
| if (value === middleElementValue) { | |
| return middleElementIndex; | |
| } | |
| if (value < middleElementValue) { | |
| return binarySearch(arr, value, start, middleElementIndex - 1); | |
| } else { | |
| return binarySearch(arr, value, middleElementIndex + 1, end); | |
| } | |
| } | |
| /* | |
| const testArray = [ 1, 3, 5, 6, 8, 99 ]; | |
| if (binarySearch(testArray, 8) !== testArray.indexOf(8)) { | |
| throw new Error(`BinarySearch test failed`); | |
| } | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment