二分法 binary_search
循环方式
const binarySearchByLoop = (arr = [0,1,2,3,4,5,6,7,8,9],target = 9) => {
const { length } = arr
let startIndex = 0
let endIndex = length - 1
while(startIndex <= endIndex){
const midIndex = Math.floor((startIndex + endIndex) / 2)
const value = arr[midIndex]
if(value < target){
startIndex = midIndex + 1
}else if(value > target){
endIndex = midIndex - 1
}else{
return midIndex
}
}
return -1
}
递归方式
const binarySearchByRecursion = (arr = [0,1,2,3,4,5,6,7,8,9],target = 9, startIndex = 0,endIndex = arr.length - 1) => {
if(startIndex > endIndex){
return -1
}
const midIndex = Math.floor((startIndex + endIndex) / 2)
const value = arr[midIndex]
if(value < target){
return binarySearchByRecursion(arr, target, midIndex + 1, endIndex)
}else if(value > target){
return binarySearchByRecursion(arr, target, startIndex, midIndex - 1)
}else{
return midIndex
}
}
以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号