一、四种常见的二分查找变形问题
1.查找第一个值等于给定值的元素
示例1
function bsearch(a, n, value) {
let low = 0;
let high = n - 1;
while (low <= high) {
let mid = low + ((high - low) >> 1);
if (a[mid] >= value) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (low < n && a[low] === value) {
return low;
} else {
return -1;
}
}
示例2
function bsearch(a, n, value) {
let low = 0;
let high = n - 1;
while (low <= high) {
let mid = low + ((high - low) >> 1);
if (a[mid] > value) {
high = mid - 1;
} else if (a[mid] < value) {
low = mid + 1;
} else {
if (mid == 0 || a[mid - 1] !== value) {
return mid;
} else {
high = mid - 1;
}
}
}
return -1;
}
2.查找最后一个值等于给定值的元素
function bsearch(a, n, value) {
let low = 0;
let high = n - 1;
while (low <= high) {
let mid = low + ((high - low) >> 1);
if (a[mid] > value) {
high = mid - 1;
} else if (a[mid] < value) {
low = mid + 1;
} else {
if (mid === n - 1 || a[mid + 1] !== value) {
return mid;
} else {
low = mid + 1;
}
}
}
return -1;
}
3.查找第一个大于等于给定值的元素
function bsearch(a, n, value) {
let low = 0;
let high = n - 1;
while (low <= high) {
let mid = low + ((high - low) >> 1);
if (a[mid] >= value) {
if (mid === 0 || a[mid - 1] <= value) {
return mid;
} else {
high = mid - 1;
}
} else {
low = mid + 1;
}
}
return -1;
}
4、查找第一个小于等于给定值的元素
function bsearch(a, n, value) {
let low = 0;
let high = n - 1;
while (low <= high) {
let mid = low + ((high - low) >> 1);
if (a[mid] <= value) {
if (mid == n - 1 || a[mid + 1] > value) {
return mid;
} else {
low = mid + 1;
}
} else {
high = mid - 1;
}
}
return -1;
}
二、适用性分析
1.凡事能用二分查找解决的,绝大部分我们更倾向于用散列表或者二叉查找树,即便二分查找在内存上更节省,但是毕竟内存如此紧缺的情况并不多。
2.求“值等于给定值”的二分查找确实不怎么用到,二分查找更适合用在”近似“查找问题上。比如上面讲几种变体。
三、思考
1.如何快速定位出一个IP地址的归属地?
[202.102.133.0, 202.102.133.255] 山东东营市
[202.102.135.0, 202.102.136.255] 山东烟台
[202.102.156.34, 202.102.157.255] 山东青岛
[202.102.48.0, 202.102.48.255] 江苏宿迁
[202.102.49.15, 202.102.51.251] 江苏泰州
[202.102.56.0, 202.102.56.255] 江苏连云港
假设我们有 12 万条这样的 IP 区间与归属地的对应关系,如何快速定位出一个IP地址的归属地呢?
2.如果有一个有序循环数组,比如4,5,6,1,2,3。针对这种情况,如何实现一个求“值等于给定值”的二分查找算法?