二分探索(Binary Search)コピペJavaScript

javascript

二分探索のアルゴリズムで評価式の符号の向きがどっちがどっちだか分からなくなる自分のためのメモ

function binarySearchTargetValueLeftMax(value, data) {
  let left = 0;
  let right = data.length - 1;
  let result = -1;

  while (left < right) {
    let mid = Math.floor((right + left) / 2);

    if (data[mid] <= value) {
      result = mid;
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  // 指定された値以下の最大値を返す
  return result !== -1 ? data[result] : null;
}

function binarySearchTargetValueRightMin(value, data) {
  let left = 0;
  let right = data.length - 1;
  let result = -1;

  while (left < right) {
    let mid = Math.floor((right + left) / 2);

    if (data[mid] >= value) {
      result = mid;
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }

  // 指定された値以上の最小値を返す
  return result !== -1 ? data[result] : null;
}

// 例として数値の配列を用意
const sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// 探す値
const targetValue = 7;

// 二分探索を実行
const resultLeftMax = binarySearchTargetValueLeftMax(targetValue, sortedArray);
const resultRightMin = binarySearchTargetValueRightMin(targetValue, sortedArray);

// 結果を出力
if (resultLeftMax !== null) {
  console.log(`Left Max value below or equal to ${targetValue}: ${resultLeftMax}`);
} else {
  console.log(`No value below or equal to ${targetValue} in the array.`);
}

if (resultRightMin !== null) {
  console.log(`Right Min value above or equal to ${targetValue}: ${resultRightMin}`);
} else {
  console.log(`No value above or equal to ${targetValue} in the array.`);
}

コメント

タイトルとURLをコピーしました