二分查找是一个基础的算法,二分查找就是将查找的键和子数组的中间键作比较,如果被查找的键小于中间键,就在左子数组继续查找;如果大于中间键,就在右子数组中查找,否则中间键就是要找的元素。
在开发中,需求大概有以下几种:
- 查询指定值首次出现下标
- 查询指定值最后一次出现下标
- 查询小于指定值的最大数的下标
- 查询大于指定值的最小数的下标
开发的套路都是下面代码中所示
int binFirstKSearch(int p[], int key) {
int start = 0;
int end = p.length-1;
while (start <= end) {
int mid = (start+end) >> 1;
if (p[mid] ? key) {
// ??
} else {
// ??
}
}
return ??;
}
@Test
public void test() {
int p[] = {1, 5, 6, 7, 11, 11, 11, 11, 56,68,77};
System.out.println("index=" + binFirstKSearch(p, 11));
}
变得只是操作符与返回值
基于上述需求中所示
- 查询指定值首次出现下标 即 查询数组元素等于指定值的集合中最左边的下标
int binFirstKSearch(int p[], int key) {
int start = 0;
int end = p.length-1;
while (start <= end) {
int mid = (start+end) >> 1;
if (p[mid] >= key) {
end = mid-1;
} else {
start = mid + 1;
}
}
return start;
}
- 查询指定值最后一次出现下标即 查询数组元素等于指定值的集合中最右边的下标
int binFirstKSearch(int p[], int key) {
int start = 0;
int end = p.length-1;
while (start <= end) {
int mid = (start+end) >> 1;
if (p[mid] <= key) {
start = mid + 1;
} else {
end = mid-1;
}
}
return end;
}
3.查询小于指定值的最大数的下标即 查询数组元素小于指定值的集合中最右边的下标
int binFirstKSearch(int p[], int key) {
int start = 0;
int end = p.length-1;
while (start <= end) {
int mid = (start+end) >> 1;
if (p[mid] < key) {
start = mid + 1;
} else {
end = mid-1;
}
}
return end;
}
4.查询大于指定值的最小数的下标即 查询数组元素大于指定值的集合中最左边的下标
int binFirstKSearch(int p[], int key) {
int start = 0;
int end = p.length-1;
while (start <= end) {
int mid = (start+end) >> 1;
if (p[mid] > key) {
end = mid-1;
} else {
start = mid + 1;
}
}
return start;
}
以上即为关于二分查找的总结 ,如果哪里说的不对,也请多多指教