Skip to content

Instantly share code, notes, and snippets.

@deanhume
Last active August 28, 2017 09:43
Show Gist options
  • Save deanhume/f61a1d59daafcc41b93a to your computer and use it in GitHub Desktop.
Save deanhume/f61a1d59daafcc41b93a to your computer and use it in GitHub Desktop.
A recursive binary search function
function binarySearch(sortedArray, searchValue, minIndex, maxIndex) {
'use strict';
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
// Find the value of the middle of the array
var middleIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = sortedArray[middleIndex];
// It's the same as the value in the middle - we can return!
if (currentElement === searchValue)
{
return middleIndex;
}
// Is the value less than the value in the middle of the array
if (currentElement < searchValue) {
return binarySearch(sortedArray, searchValue, middleIndex + 1, maxIndex);
}
// Is the value greater than the value in the middle of the array
if (currentElement > searchValue) {
return binarySearch(sortedArray, searchValue, minIndex, middleIndex - 1);
}
}
return -1;
}
// The array with all of our numbers
var sortedArray = [1,2,4,5,10,12,44,89,99,304];
// The value we are looking for in the array
var valueToFind = 89;
// The starting index point in the array
var minIndex = 0;
// The full size of the array
var maxIndex = sortedArray.length - 1;
var result = binarySearch(sortedArray, valueToFind, minIndex, maxIndex);
console.log('The index position is: ', result);
console.log('The value is: ', sortedArray[result]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment