直接考虑有重复元素的情况
查找右边:
#include<stdio.h>
int dichotomy(int arr[9],int n,int x)
{
int left=-1;int right=n;int mid;
while(left+1<right){
mid=(left+right)>>1;
if(arr[mid]>x) right=mid;
else left=mid;
}
return left;
}
int main(){
int arr[9];
for(int i=0;i<9;i++){
scanf("%d",&arr[i]);
}
int target= dichotomy (arr,9,5)+1;
printf("%d",target);
}
查找左边:
#include<stdio.h>
int dichotomy(int arr[9],int n,int x)
{
int left=-1;int right=n;int mid;
while(left+1<right){
mid=(left+right)>>1;
if(arr[mid]<x) left=mid;
else right=mid;
}
return right;
}
int main(){
int arr[9];
for(int i=0;i<9;i++){
scanf("%d",&arr[i]);
}
int target= dichotomy (arr,9,5)+1;
printf("%d",target);
}
对于非重复的查找以上任意一种均可实现