查找⽐较简单,我们先来看⼀个经典的⼆分查找 有点类似幸运52的猜价格,⽐如让你在1和1000之间猜个数字,挨个猜是很蠢的,要先猜500,如果⼤了,那就是0~500 ,每次问题减半,很快就能查到
function binarySeatch(arr,target) {
var low=0,
high=arr.length-1,
mid;
while(low<=high){
mid=Math.floor((low+high)/2);
if(target===arr[mid]){
return `找到了${target},在第${mid + 1}个`
}
if(target>arr[mid]){
low=mid+1;
}else if(target<arr[mid]){
high=mid-1
}
}
return -1
}
console.log(binarySeatch([1,2,3,4,5,6],2))
function binarySearch1(arr,target,low=0,high=arr.length-1) {
const n=Math.floor((low+high)/2);
const cur=arr[n];
if(cur===target){
return `找到了${target},在第${mid + 1}个`
}else if(cur>target){
return binarySearch1(arr,target,low,n-1)
}else if(cur<target){
return binarySearch1(arr,target,n+1,high)
}
return -1
}