递归实现
var arr = [1, 2, 4, 5, 6, 7, 39]
function binSearch(start, end, arr, target) {
let mid = Math.floor((end - start) / 2 )+ start
if (start > end ) return - 1
console.log(start, end, mid)
if (arr[mid] === target) {
return mid
} else if (arr[mid] < target) {
return binSearch(mid + 1, end, arr, target)
} else {
return binSearch(start, mid - 1, arr, target)
}
return -1
}
非递归实现
var arr = [1, 2, 4, 5, 6, 7, 39]
function binSearch(arr, target) {
let start = 0
let end = arr.length
while(start <= end) {
let mid = Math.floor((end - start) / 2)+ start
if (arr[mid] === target) {
return mid
} else if (arr[mid] < target) {
start = mid + 1
} else {
end = mid - 1
}
}
}
binSearch(arr, 6)
为什么这么简单的题都答不出来。。
网友评论