📜  binarySearch - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:03.345000             🧑  作者: Mango

代码示例1
function binarySearch(list, item) {
  let min = 0;
  let max = list.length - 1;
  let guess;

  while (min <= max) {
    guess = Math.floor((min + max) / 2);

    if (list[guess] === item) return item;

    if (list[guess] < item) {
      min = guess + 1;
    } else {
      max = guess - 1;
    }
  }
  return -1;
}

console.log(binarySearch([2, 6, 7, 90, 108], 90));