Skip to content

Instantly share code, notes, and snippets.

@zbicin
Last active November 17, 2021 17:20
Show Gist options
  • Save zbicin/6887e370053e28b858cb5a304b822167 to your computer and use it in GitHub Desktop.
Save zbicin/6887e370053e28b858cb5a304b822167 to your computer and use it in GitHub Desktop.
Binary Search implementation in JavaScript
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