FrontEndCollection icon indicating copy to clipboard operation
FrontEndCollection copied to clipboard

Binary Search

Open cheatsheet1999 opened this issue 4 years ago • 0 comments

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

Screen Shot 2021-09-09 at 1 17 20 PM
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var search = function(nums, target) {
    let start = 0;
    let end = nums.length - 1;
    while(start <= end) {
        let mid = Math.floor((start + end) / 2);
        if(nums[mid] === target) {
            return mid;
        }
        else if(target > nums[mid]) {
            start = mid + 1;
        }
        else if(target < nums[mid]) {
            end = mid - 1;
        }
    }
    return -1;
};

cheatsheet1999 avatar Sep 09 '21 20:09 cheatsheet1999