有序数组
递归实现
function binerySearch(item,arr,start,end){
var start = start || 0
var end = end || arr.length-1
var mid = Math.floor((start+end)/2)
if(item === arr[mid]){
return mid
}else if(item>arr[mid]){
return binerySearch(item,arr,mid+1,end)
}else{
return binerySearch(item,arr,start,mid-1)
}
return false
}
var a=[1,2,3,4,5,6,7,8,9]
console.log(binerySearch(5,a))
非递归实现
function binerySearch(item,arr){
var start = 0;
var end = arr.length-1;
var newArr = arr.sort(function(){
return a-b
})
while(start<=end){
var mid = Math.floor((start+end)/2)
if(item===arr[mid]){
return mid
}else if(item<arr[mid]){
end = mid-1
}else{
start = mid +1
}
}
return false
}
var a=[1,2,3,4,5,6,7,8,9]
console.log(binerySearch(5,a))
网友评论