二进制搜索功能是正确的,但它 returns 未定义

binary search function is correct but it returns undefined

我有这个功能可以做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;

}

此函数returns仅当我要搜索的键的索引,equals原始数组的中间。否则,returns 未定义。

示例:

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

请查看更新后的代码,使用递归函数时需要return 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;

}