Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active July 27, 2018 06:09
Show Gist options
  • Save bradoyler/d6db8c4223c9d855e324 to your computer and use it in GitHub Desktop.
Save bradoyler/d6db8c4223c9d855e324 to your computer and use it in GitHub Desktop.
search an array with binary search algorithm - iterative & recursive approaches
// iterative approach
function binarySearch(arr, searchElement) {
var minIndex = 0;
var maxIndex = arr.length - 1;
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = arr[currentIndex];
if (currentElement < searchElement) {
minIndex = currentIndex + 1;
}
else if (currentElement > searchElement) {
maxIndex = currentIndex - 1;
}
else {
return currentIndex;
}
}
return -1;
}
//recursive approach: http://cwestblog.com/2012/03/19/javascript-binary-search/
function binarySearch(arr, item, min, max, fnCmp) {
if(min > max) {
return -1;
}
var mid = parseInt((min + max) / 2);
var ret = fnCmp(item, arr[mid]);
if(ret) {
return binarySearch(arr, item,
ret > 0 ? mid + 1 : min,
ret < 0 ? mid - 1 : max, fnCmp);
}
else if(ret == 0) {
return mid;
}
}
function fnExact(a, b) {
    return a < b ? -1 : a > b ? 1 : a === b ? 0 : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment