JS数组的二分查找算法
2020-03-19 本文已影响0人
喜剧之王爱创作
用途:对有序数组进行查找。如:查找指定元素在数组中的下标
/*
@param {number} target 查找的目标值
@param {array} arr 被查找的数组
@return {number} target所在的数组下标位置
*/
function binarySearch(target,arr) {
var start = 0;
var end = arr.length-1;
while (start<=end){
var mid = parseInt(start+(end-start)/2);
if(target==arr[mid]){
return mid;
}else if(target>arr[mid]){
start = mid+1;
}else{
end = mid-1;
}
}
return -1;
}
//递归写法(和上面一样,只是拆成了递归)
function binarySearch(target,arr,start,end) {
var start = start || 0;
var end = end || arr.length-1;
var mid = parseInt(start+(end-start)/2);
if(target==arr[mid]){
return mid;
}else if(target>arr[mid]){
return binarySearch(target,arr,mid+1,end);
}else{
return binarySearch(target,arr,start,mid-1);
}
return -1;
}