思路:
1、输入:数组长度n,待查找的有序数组a[],要找的元素key
2、输出:待查找元素在数组中的位置,若不存在返回-1
3、实现:三个指针,left、mid、right
#include<stdio.h>
int binarySearch(int a[],int key,int n);
int main(){
int n,i,key,result,a[];
scanf("%d",&n);
scanf("%d",&key);
for(i = ;i<n;i++){
scanf("%d",&a[i]);
}
result = binarySearch(a,key,n);
printf("%d",result);
}
int binarySearch(int a[],int key,int n){
int left = ;
int right = n-;
while(left<=right){
int mid = (left+right)/;
if(a[mid]==key) return mid;
else if(a[mid]<=key) left = mid + ;
else right = mid - ;
}
return -;
}