使用 JavaScript 中的二分搜索来搜索查询

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/29 11:24:17

我们需要编写一个 JavaScript 函数,该函数将已排序的文字数组作为第一个参数,将查询文字作为第二个参数。然后我们的函数应该使用二分搜索算法来查找查询是否存在于数组中。

如果存在,我们返回其在数组中的索引,否则我们返回 -1。

示例

其代码为 −

const arr = [1, 2, 3, 5, 6, 7, 10, 11, 14, 15, 17, 19, 20, 22, 23];
const binarySearch = (arr, query) => {
   let index = Math.floor(arr.length / 2);
   if (arr[index] === query){
      return index;
   }else if (arr.length === 1){
      return null;
   }else if (arr[index] < query) {
      arr = arr.slice(index + 1);
      let res = binarySearch(arr, query);
      if (res === null){
         return -1;
      }else {
         return index + 1 + res;
      };
   }else {
      let arr1 = arr.slice(0, index);
      return binarySearch(arr1, query);
   };
};
console.log(binarySearch(arr, 1));
console.log(binarySearch(arr, 7));
console.log(binarySearch(arr, 11));
console.log(binarySearch(arr, 12));
console.log(binarySearch(arr, 22));

输出

控制台中的输出 −

0
5
7
-1
13

相关文章


有用资源