// while实现
function dichotomy (numlist, value) {
let min = 0
let max = numlist.length - 1
while(min <= max) {
let middleIndex = parseInt((min + max) / 2)
let item = numlist[middleIndex]
if (item === value) {
return middleIndex
} else if (item > value) {
max = middleIndex - 1
} else if (item < value) {
min = middleIndex + 1
} else {
return -1
}
}
}
// 递归实现
function recurrence (numlist, value, min = 0, max = numlist.length - 1 ) {
let middleIndex = parseInt((min + max) / 2)
let item = numlist[middleIndex]
if (item === value) {
return middleIndex
} else if (item > value) {
max = middleIndex - 1
return recurrence(numlist, value, min, max )
} else if (item < value) {
min = middleIndex + 1
return recurrence(numlist, value, min, max)
} else {
return -1
}
}
console.log(dichotomy([1,2,3,4,5,6,7], 7))
console.log(recurrence([1,2,3,4,5,6,7], 5))
console