使用 JavaScript 使用二进制搜索在数组中搜索
问题
我们需要编写一个JavaScript函数,它接受一个排序的数字数组(递增顺序),arr作为第一个参数,一个目标数字作为第二个参数。由于数组已排序,我们的函数应该使用二进制搜索算法在数组arr中搜索目标。
如果目标存在,那么我们应该返回它的索引,否则我们应该返回-1。
例如,如果函数的输入是
输入
const arr = [3, 5, 7, 9, 11, 13, 15, 16, 18, 21, 24, 25, 28]; const target = 13;
输出
const output = 5;
示例
以下是代码-
const arr = [3, 5, 7, 9, 11, 13, 15, 16, 18, 21, 24, 25, 28];
const target = 13;
const binarySearch = (arr = [], target) => {
const helper = (low, high) => {
if (low > high) {
return -1
}
const middle = Math.floor((low + high) / 2)
if (arr[middle] === target) {
return middle
} if (arr[middle] < target) {
return helper(middle + 1, high)
}
return helper(low, middle - 1)
}
return helper(0,arr.length- 1)
};
console.log(binarySearch(arr, target));输出结果5
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下