Last active
September 18, 2019 18:36
-
-
Save greathmaster/13e4c8888f62ffb337adb8fcf030470d to your computer and use it in GitHub Desktop.
Binary Search in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Iterative Solution | |
var bsearchIter = function(nums, target) { | |
let [left, right] = [0, nums.length-1]; | |
while(left <= right) { | |
let mid = Math.floor((left + right)/2); | |
if(target < nums[mid]) { | |
right = mid-1; | |
} else if(target > nums[mid]){ | |
left = mid+1; | |
}else { | |
return mid; | |
} | |
} | |
return -1; | |
}; | |
//Recursive Solution | |
var bSearchRec = function(nums, target, left, right) { | |
if(nums.length === 0) | |
return -1; | |
let guess_index = Math.floor((left + right)/2); | |
let guess = nums[guess_index]; | |
if(guess == target) | |
return guess_index; | |
if(left == right) | |
return -1; | |
if(target < guess) { | |
return bSearchRec(nums, target, left, guess_index); | |
} | |
else { | |
return bSearchRec(nums, target, guess_index + 1, right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment