Basic Javascript Binary Search

  • 0

    Couldn't initially understand the fancy iterative binary search solutions of other posts where you set low as mid+1 and high as mid, so I tried a more generic binary search way, the way we were taught in school. It works as well!

    If someone can explain to my why the cool way of only needing to set high to mid, as opposed to mid-1, that would be appreciated.

        var findPeak5 = function(nums){
            var lowIndex = 0;
            var highIndex = nums.length - 1;
            while(lowIndex < highIndex){
                var middleIndex = Math.floor((lowIndex + highIndex)/2);
                if(nums[middleIndex] < nums[middleIndex-1]){
                    highIndex = middleIndex-1;
                }else if(nums[middleIndex] < nums[middleIndex+1]){
                    lowIndex = middleIndex+1;
                    return middleIndex;
            return lowIndex;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.