Skip to content

Instantly share code, notes, and snippets.

@deanhume
Last active February 16, 2016 15:18
Show Gist options
  • Save deanhume/02f36c45c02137b051bf to your computer and use it in GitHub Desktop.
Save deanhume/02f36c45c02137b051bf to your computer and use it in GitHub Desktop.
A simple binary search function
function binarySearch(searchValue) {
'use strict';
var minIndex = 0;
var maxIndex = sortedArray.length - 1;
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = sortedArray[currentIndex];
// 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) {
minIndex = currentIndex + 1;
}
// Is the value greater than the value in the middle of the array
if (currentElement > searchValue) {
maxIndex = currentIndex - 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;
var result = binarySearch(sortedArray, valueToFind);
console.log('The index position is: ', result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment