javascript - 二分查找函数是正确的,但返回未定义

标签 javascript algorithm binary-search

我有这个函数来进行二分搜索

const binarySearch = (array, value) => {
    let min = 0;
    let max = array.length - 1;
    return doBinary(array, min, max, value);
};

/**
* DoBinary
*/

function doBinary(arr, min, max, key) {
    let med = Math.floor((min + max) / 2);
    let diff = max - min;
    if (arr[med] === key) {
          console.log(med) // <====================== med here is correct, but it returns only undefined
          return  med;   // <========================= problem in this line
/*
* Returns only if the Index of the key that I'm searching for, `equals` the middle of the original array
* otherwise, returns undefined,
*/
         }
    else if (diff > 0 && arr[med] < key) {
        min = med + 1;
        doBinary(arr, min, max, key);
    }
    else if (diff > 0 && arr[med] > key) {
        max = med - 1;
        doBinary(arr, min, max, key);

    }
    else return -1;

// return med;

}

仅当我正在搜索的键的索引等于原始数组的中间时,此函数才会返回。否则,返回未定义。

示例:

A = [1,2,3,4,5];
binarySearch(A, 1) //undifined
binarySearch(A, 2) //undifined
binarySearch(A, 3) //2
binarySearch(A, 4) //undifined
binarySearch(A, 5) //undifined

最佳答案

请查看更新后的代码,使用递归函数时需要返回 doBinary 响应。

function doBinary(arr, min, max, key) {
  let med = Math.floor((min + max) / 2);
  let diff = max - min;
  if (arr[med] === key) {
    console.log(med) // <====================== med here is correct, but it returns only undefined
    return med;   // <========================= problem in this line
    /*
    * Returns only if the Index of the key that I'm searching for, `equals` the middle of the original array
    * otherwise, returns undefined,
    */
  }
  else if (diff > 0 && arr[med] < key) {
    min = med + 1;
    return doBinary(arr, min, max, key);
  }
  else if (diff > 0 && arr[med] > key) {
    max = med - 1;
    return doBinary(arr, min, max, key);

  }
  else return -1;

  // return med;

}

关于javascript - 二分查找函数是正确的,但返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61585873/

相关文章:

javascript - Divs/spans 作为输入类型,带有 $_POST 信息,其中哪一个被单击

javascript - 在 JavaScript 中从另一个对象创建对象

javascript - 仅当未定义 AngularJS 时才通过

C++二进制搜索没有成功运行......永远

algorithm - 在一个数组中进行二进制搜索,除了两个元素之外,所有元素都被排序,即所有元素都被排序,然后交换两个相邻元素?

javascript - 完整日历: start calendar with a specific week

algorithm - 生成彼此相邻的数字组

algorithm - 弗洛伊德-沃歇尔算法

algorithm - 采访问题: Identify Unique Pair in Stream of data

python - 在二进制搜索中,为什么 mid = (left + (right - left))//2 比 mid = (left + right)//2 好?