Last active
August 7, 2020 01:53
-
-
Save GAierken/227e425a15081d78ca85d5ed9dd75b6f to your computer and use it in GitHub Desktop.
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
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