二分查找模板
// 标准二分查找,使用数组能找到的情况,最后left和right不一样,差1
function find(arr, num) {
let l = 0, r = arr.length - 1;
while (l <= r) {
let mid = l + Math.floor((r - l) / 2)
if (arr[mid] === num) {
return num
} else if (arr[mid] > num) {
r = mid - 1
} else {
l = mid + 1
}
}
console.log(l, r);
return '没找到'
}
find([1,2,3,4,5],3)
find([1,2,4,5],3)
// 适合查找大于等于target的第一个值,最后left和right相等
function find(arr, num) {
let l = 0, r = arr.length - 1;
while (l < r) {
let mid = Math.floor((r + l) / 2)
if (arr[mid] === num) {
return num
} else if (arr[mid] > num) {
r = mid
} else {
l = mid + 1
}
}
console.log(l, r);
return arr[l]
}
find([1,2,5,6,7],3)
find([1,2,3,4,5],3)
find([1,2,4,5],3)
// 适合查找小于等于target的第一个值,最后left和right相等
function find(arr, num) {
let l = 0, r = arr.length - 1;
while (l < r) {
let mid = Math.floor((r + l) / 2) + 1
if (arr[mid] === num) {
return num
} else if (arr[mid] > num) {
r = mid - 1
} else {
l = mid
}
}
console.log(l, r);
return arr[l]
}
find([1,2,3,4,5],3)
find([1,2,4,5],3)