【问题标题】:BinarySearch on javascriptjavascript 上的二进制搜索
【发布时间】:2020-07-17 18:49:17
【问题描述】:

好吧,给定一个有序数组,使用称为二分查找的方法查找作为参数传递的特定元素的索引。如果在数组中找不到搜索到的数字,则返回 -1。

例子:

array = [1,2,3,4,5,6,7,8,9,10];
binarySearch (array, 2) -> Would return 1 since array [1] = 2
[Where 2 would be the number on which we want to know its position in the array]

我试过了

var binarySearch = function (array, target) {
  var start = 0;
  var end = array.length-1
  while (start <= end) {
    let mid=Math.floor((start + end)/2);
    if (array[mid]===target) {
      return true;
    } else if (array[mid] < target) {
      start = mid + 1;
    } else {
      end = mid - 1;
    }
  }
  return array;

}

但不工作是不是做错了什么?

AssertionError: expected true to equal 4

      160 | });
      161 | it ('Should return 4 for array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if bu
sca 5 ', function () {
    > 162 | expect (binarySearch ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)). to.equal (4);
      163 | });
      164 |
      165 | it ('It should return -1 if it can't find the value searched in the array', fun
ction () {

【问题讨论】:

  • 该任务希望您返回一个数字,该数字是元素的索引(在本例中为 4)。但是您正在返回true。尝试返回mid。同样当你没有找到它时,你返回array,但任务要求你返回-1...

标签: javascript binary binary-search-tree binary-search


【解决方案1】:

您应该返回一个索引或 -1,而不是 truearray。查看演示:

var array = [1,2,3,4,5,6,7,8,9,10];

var binarySearch = function (array, target) {
  var start = 0;
  var end = array.length-1
  while (start <= end) {
    let mid=Math.floor((start + end)/2);
    if (array[mid]===target) {
      return mid;
    } else if (array[mid] < target) {
      start = mid + 1;
    } else {
      end = mid - 1;
    }
  }
  return -1;
}

console.log(binarySearch(array, 2));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多