Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

第 30 期(算法-搜索):二分搜索算法 #33

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

题目:

请使用 二分搜索算法 编写函数 binarySearch,实现类似 indexOf 的功能。要求:

  • 不要用递归方式实现;
  • 避免产生副作用(即不能修改原数组)。
/**
 * @param {array} arr - 按升序排列的普通数组
 * @param {number} target - 需要在 arr 中搜索的目标值
 * @return {number} 返回 target 在 arr 中的索引值,如不存在,则返回 -1
 */
function binarySearch(arr, target) {
  // 你的代码
}

测试数据:

const test = [1, 3, 8, 9, 27, 34, 128, 275];

binarySearch(test, 128);  // 6
binarySearch(test, 30);  // -1

参考答案:

function binarySearch(arr, target) {
  let startIdx = 0;
  let endIdx = arr.length - 1;
  let midIdx = Math.floor((startIdx + endIdx) / 2);

  while(endIdx - startIdx > 1) {
    switch(target) {
      case arr[startIdx]: return startIdx;
      case arr[endIdx]: return endIdx;
      case arr[midIdx]: return midIdx;
    }

    if (target > arr[midIdx]) {  // 右边找
      startIdx = midIdx;
    } else if (target < arr[midIdx]) {  // 左边找
      endIdx = midIdx;
    }

    midIdx = Math.floor((startIdx + endIdx) / 2);
  }

  return -1;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.