递归写法
let binarySearch_recursion = function(nums, target, left = 0, right = nums.length - 1) {
if(left > right) return -1
let mid = Math.floor((right + left) / 2)
if(nums[mid] == target) {
return mid
}else if(nums[mid] < target) {
return binarySearch_recursion(nums, target, mid + 1, right)
}else {
return binarySearch_recursion(nums, target, left, mid - 1)
}
}
迭代写法
let binarySearch = function(nums, target, left = 0, right = nums.length - 1){
if(left > right) return -1
while(left <= right) {
let mid = left + ((right - left) >> 1)
if(nums[mid] == target) {
return mid
}else if(nums[mid] < target) {
left = mid + 1
}else {
right = mid - 1
}
}
return left
}