JavaScript Binary Search

var binarySearch = function(arr, target)
{
    var startIndex = 0;
    var endIndex = arr.length - 1;

    while(startIndex <= endIndex)
    {
        var middleIndex = Math.floor((startIndex + endIndex) / 2);

        if (target > arr[middleIndex])
            startIndex = middleIndex+ 1;

        if (target < arr[middleIndex])
            endIndex = middleIndex - 1;

        if (target == arr[middleIndex])
            return middleIndex;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *