二进制搜索由于索引不起作用?

时间:2019-05-30 06:55:01

标签: javascript algorithm binary-search

我正在看this binary search

我对索引进行了一些修改,但无法使其正常工作

function bs1(a, tar, l, h) {
  // pass index, so equal
  if (h > l) { 
    // not m = (h+l)/2
    // l+diff
    //let m = l + Math.floor( (h - l) / 2 ); 
    let m = Math.floor( (h + l) / 2 ); 

    if (a[m] == tar) 
      return m; 

    // tar... a[m]....
    if (a[m] > tar) 
        return bs1(a, tar, l, m - 1); 

    // a[m]..tar...
    return bs1(a, tar, m + 1, h); 
  }

  return -1;
}

arr = [1, 2, 3, 4, 5, 6, 7];
tar = 5;
out = bs1(arr, tar, 0, arr.length);
console.log(out);

我想做的是:

  • 通过arr.length,而不是arr.length-1

  • 使用if (h > l) {代替if (h >= l) {

有可能吗?

1 个答案:

答案 0 :(得分:1)

尝试执行此操作(进行小小的更改)->返回索引4,这是预期的fiddle

function bs1(a, tar, l, h) {

  // pass index, so equal
  if (h > l) { 
    // not m = (h+l)/2
    // l+diff
    //let m = l + Math.floor( (h - l) / 2 ); 
    let m = Math.floor( (h + l) / 2 ); 

    if (a[m] == tar) 
      return m; 

    // tar... a[m]....
    if (a[m] > tar) 
        return bs1(a, tar, l, m); 

    // a[m]..tar...
    return bs1(a, tar, m + 1, h); 
  }

  return -1;
}

arr = [1, 2, 3, 4, 5, 6, 7];
tar = 5;
out = bs1(arr, tar, 0, arr.length);
console.log(out);