Skip to content

Instantly share code, notes, and snippets.

@jmjuanes
Created March 9, 2016 11:55
Show Gist options
  • Select an option

  • Save jmjuanes/27ec89ccf06fa60b1ee9 to your computer and use it in GitHub Desktop.

Select an option

Save jmjuanes/27ec89ccf06fa60b1ee9 to your computer and use it in GitHub Desktop.

Revisions

  1. jmjuanes created this gist Mar 9, 2016.
    51 changes: 51 additions & 0 deletions FindBinary.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    //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;