1. 经典的二分查找:
/*
num:待查找数组
[begin, end] :查找区间
keyValue:待查找关键字
*/
int binaraySearch(int* num , int begin, int end, int keyValue){
int mid;
while(begin <= end){
mid = begin + (end - begin) / 2;
if(num[mid] == keyValue)return mid;
else if(keyValue > num[mid])begin = mid + 1;
else end = mid - 1;
}
return -1;
}
2.查找第一个与keyValue相等的元素:
int binaraySearch(int* num , int begin, int end, int keyValue){
int mid, preBegin = begin;
while(begin <= end){
mid = begin + (end - begin) / 2;
if(num[mid] == keyValue){
if(begin == preBegin || num[begin - 1] != keyValue)return mid;//看是否是最左边的一个
end = mid - 1;//如果不是继续缩小区间
}else if(num[mid] > keyValue){
end = mid - 1;
}else{
begin = mid + 1;
}
}
return -1;
}
3.查找最后一个与keyValue相等的元素:
using namespace std;
int binaraySearch(int* num , int begin, int end, int keyValue){
int mid, preEnd = end;
while(begin <= end){
mid = begin + (end - begin) / 2;
if(num[mid] == keyValue){
if(mid == preEnd || num[mid + 1] != keyValue)return mid;
begin = mid + 1;
}else if(num[mid] > keyValue){
end = mid - 1;
}else{
begin = mid + 1;
}
}
return -1;
}
4.查找第一个等于或者大于keyValue的元素:
int binaraySearch(int* num , int begin, int end, int keyValue){
int mid, preBegin = begin;
while(begin <= end){
mid = begin + (end - begin) / 2;
if(num[mid] >= keyValue){
if(mid == preBegin || num[mid - 1] < keyValue)return mid;
end = mid - 1;
}else{
begin = mid + 1;
}
}
return -1;
}
5.查找第一个大于keyValue的运算:
int binaraySearch(int* num , int begin, int end, int keyValue){
int mid, preBegin = begin;
while(begin <= end){
mid = begin + (end - begin) / 2;
if(num[mid] > keyValue){
if(mid == preBegin || num[mid - 1] <= keyValue)return mid;
end = mid - 1;
}else{
begin = mid + 1;
}
}
return -1;
}
6.查找最后一个小于keyValue的元素:
int binaraySearch(int* num , int begin, int end, int keyValue){
int mid, preEnd = end;
while(begin <= end){
mid = begin + (end - begin) / 2;
if(num[mid] < keyValue){
if(mid == preEnd || num[mid + 1] >= keyValue)return mid;
begin = mid + 1;
}else{
end = mid - 1;
}
}
return -1;
}
核心思想:
当找到某种情况,要看是否是需要的,如果不是,则继续缩小范围
如果错误,希望各位在下面指出!! daversun