Skip to content
On this page

二分搜索

二分搜索的的前提是有序数组,使用系统内置的 sort() 方法,时间复杂度一般是 O(NLogN)

Code

function binarySearch(nums, target) {
  let left = 0,
    right = nums.length - 1,
    mid;
  while (left <= right) {
    mid = Math.floor(left + (right - left) / 2);
    let val = nums[mid];
    if (val === target) {
      return mid;
    } else if (val > target) {
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }
  return -1;
}

Test Cases

const { binarySearch } = require('./binarySearch');
describe('binarySearch', () => {
  it('case1', () => {
    const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    const target = 8;
    expect(binarySearch(nums, target)).toBe(nums[nums.length - 2]);
  });
});