# 通俗易懂的二分查找及其变体问题

### 简单的二分查找

int binarySearch(int A[], int n, int x){

//left 和right为数组的左右区间下标
int left = 0, right =n-1, mid;
while(left <= right){
mid = left + ( right - left) / 2; //当数组数量较多时为了防止left+right超过int范围。
if(A[mid] == x) return mid; //找到x，返回下标
else if(A[mid] > x){
right = mid-1;
} else{
left = mid+1;
}
}
return -1; //没有找到，返回-1。
}

### 二分查找变体：

#### 查找序列中第一个等于x的元素的位置

//查找第一个等于x的位置
int findfirstX(int A[], int n, int x){
int left = 0, right = n-1;
int mid;
while(left <= right){
mid = left + ((right-left) >> 1);
if(A[mid] > x){
right = mid-1;
}else if(A[mid] < x){
left = mid + 1;
}else{
if(mid == 0 || A[mid-1] != x) return mid;
else right = mid-1;
}
}
return -1;
}

#### 查找序列中最后一个等于给定值的元素

//查找最后一个等于x的元素位置
int findlastX(int A[], int n, int x){
int left = 0, right = n-1, mid;
while(left <= right){
mid = left + ((right-left) >> 1);
if(A[mid] > x){
right = mid-1;
}else if(A[mid] < x){
left = mid + 1;
}else{
if(mid == n-1 || A[mid+1] != x) return mid;
else left = mid+1;
}
}
return -1;
}

#### 查找序列中第一个大于等于x的元素的位置

//查找第一个大于等于x的元素位置
int Upperfind(int A[], int n, int x){
int left = 0, right = n-1, mid;
while(left <= right){
mid = left + ((right-left) >> 1);
if(A[mid] >= x){
if((mid==0) || (A[mid-1] < x)) return mid;
else right = mid-1;
}else{
left = mid+1;
}
}
} 

#### 查找序列中最后一个小于等于x的元素的位置

//查找最后一个小于等于x的元素位置
int boundfind(int A[], int n, int x){
int left =0, right = n-1, mid;
while(left <= right){
mid = left + ((right- left) >> 1);
if(A[mid] <= x){
if((mid==n-1) || (A[mid+1] > x)) return mid;
else left = mid+1;
}else{
right = mid-1;
}
}
} 

#### 查找序列中第一个大于x的元素的位置

//查找第一个大于x的元素位置
int findlargeX(int A[], int n, int x){
int left =0 ,right = n-1, mid;
while(left <= right){
mid = left + ((right- left) >> 1);
if(A[mid] > x){
if((mid==0) || (A[mid-1] < x)) return mid;
else right = mid - 1;
}else{
left = mid + 1;
}
}
return -1;
} 

posted @ 2019-12-03 21:27  huanghh  阅读(...)  评论(... 编辑 收藏