Skip to content

Instantly share code, notes, and snippets.

@GAierken
Last active August 7, 2020 01:53
Show Gist options
  • Save GAierken/227e425a15081d78ca85d5ed9dd75b6f to your computer and use it in GitHub Desktop.
Save GAierken/227e425a15081d78ca85d5ed9dd75b6f to your computer and use it in GitHub Desktop.
const search = (nums, target) => {
// declare start and end
let start = 0
let end = nums.length - 1
// base condition
while(start <= end){
// find the mid point
let mid = Math.floor((start+end)/2)
// if middle element is the target, return middle index
if(nums[mid] === target){
return mid
// if middle element is smaller, move the start point to mid + 1
}else if(nums[mid] < target){
start = mid + 1
// if middle element it greater, move the end point to mid - 1
}else{
end = mid - 1
}
}
// if not found, return -1
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment