二分查找(binary search)的四种实现方式

以下为javascript实现二分查找(binary search)的四种实现方式,其中第一种为递归写法,其他三种为迭代写法。

递归写法(recursive approach)

const binarySearchRecursive = (nums, left, right, target) {
  if (right <= left) {
    return -1;
  }
  
  const mid = left + Math.floor((right - left) / 2);
  if (nums[mid] > target) {
    return binarySearchRecursive(nums, left, mid - 1, target);
  } else if (nums[mid] < target) {
    return binarySearchRecursive(nums, mid + 1, right, target);
  }
  return mid;
};

迭代写法1:left <= right

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

迭代写法2: left < right

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

你可能感兴趣的:(二分查找(binary search)的四种实现方式)