当前位置: 代码迷 >> JavaScript >> 从二进制搜索功能返回值
  详细解决方案

从二进制搜索功能返回值

热度:26   发布时间:2023-06-12 14:09:12.0

以下代码对数组进行二进制搜索。 我做了艰苦的工作,并获得了理论上可以运行的代码; 不幸的是,我很难从函数中返回值。

简而言之,我希望返回“ len”; 如果在该行中设置断点,您将看到“ len”包含正确的答案。 但是我错过了一些非常愚蠢的东西。 请帮助我识别。

var states = ['Alabama','Alaska','American Samoa','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Federated States of Micronesia','Florida','Georgia','Guam','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Marshall Islands','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Northern Mariana Islands','Ohio','Oklahoma','Oregon','Palau','Pennsylvania','Puerto Rico','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virgin Island','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
function binarySearch(arr1,term){
  var arr = [...arr1],
    len = 0;
  function helper(arr,term) {
    if(arr.length > 1) {
      if(arr[Math.floor(arr.length/2)] === term) {
          len += Math.floor(arr.length/2);
          return len;
      }
      if(arr[Math.floor(arr.length/2)] < term) {
          len += Math.floor(arr.length/2);
          arr.splice(0,Math.floor(arr.length/2));
          helper(arr,term)
      }
      else if (arr[Math.floor(arr.length/2)] > term) {
          arr.splice(Math.floor(arr.length/2),arr.length-1);
          helper(arr,term)
      }
    } else {
        return 'Element not found';
    }
  }
  return helper(arr,term);
}
console.log(binarySearch(states,"Arizona"));

您的递归调用也应该返回给调用者:

更换:

helper(arr,term)

有:

return helper(arr,term)

在这两种情况下。

  相关解决方案