(no title)
atfzl | 4 years ago
https://leetcode.com/problems/binary-search/
JavaScript code:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
// empty arr, so we won't find anything
if (!arr.length) {
return -1;
}
// the target is less than the smallest number in arr
if (target < arr[left]) {
return -1;
}
// the target is greater then the smallest number in arr
if (arr[right] < target) {
return -1;
}
// These two `if` are needed for the case when there are only 2 elements
// in the array.
if (arr[left] === target) {
return left;
}
if (arr[right] === target) {
return right;
}
while (left + 1 !== right) {
const middle = left + Math.floor((right - left) / 2);
if (arr[middle] < target) {
left = middle;
} else {
right = middle;
}
}
if (arr[right] === target) {
return right;
}
return -1;
}
No comments yet.