使用JavaScript中的二进制搜索来搜索查询
我们需要编写一个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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短