Skip to content

Instantly share code, notes, and snippets.

@jmjuanes
Created March 9, 2016 11:55
Show Gist options
  • Save jmjuanes/27ec89ccf06fa60b1ee9 to your computer and use it in GitHub Desktop.
Save jmjuanes/27ec89ccf06fa60b1ee9 to your computer and use it in GitHub Desktop.
Binary search in an array.
//Function for find the position in a cover array
function FindBinary(arr, position)
{
//Get the min index
var minIndex = 0;
//Get the max index
var maxIndex = arr.length - 1;
//Check the array start
if(position <= arr[minIndex]){ return minIndex; }
//Check the array end
if(arr[maxIndex] <= position){ return maxIndex; }
//Find the element
while(minIndex <= maxIndex)
{
//Get the middle point
var middle = Math.floor((maxIndex + minIndex)/2);
//Check <
if(arr[middle] < position)
{
//Check the next element
if(position < arr[middle + 1] ){ return middle; }
//Else, update the min index
minIndex = middle + 1;
}
else if(position < arr[middle] )
{
//Check the prev element
if(arr[middle - 1] < position){ return middle; }
//Else, update the max index
maxIndex = middle - 1;
}
else
{
//Return the middle point
return middle;
}
}
//Default, return min value
return minIndex;
}
//Exports to node
module.exports = FindBinary;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment