思路:

1、输入:数组长度n,待查找的有序数组a[],要找的元素key

2、输出:待查找元素在数组中的位置,若不存在返回-1

3、实现:三个指针,left、mid、right

 1 #include<stdio.h>
 2 int binarySearch(int a[],int key,int n);
 3 int main(){
 4     int n,i,key,result,a[100];
 5     scanf("%d",&n);
 6     scanf("%d",&key);
 7     for(i = 0;i<n;i++){
 8         scanf("%d",&a[i]);
 9     }
10     result = binarySearch(a,key,n);
11     printf("%d",result);
12 }
13 int binarySearch(int a[],int key,int n){
14     int left = 0;
15     int right = n-1;
16     while(left<=right){
17         int mid = (left+right)/2;
18         if(a[mid]==key) return mid;
19         else if(a[mid]<=key) left = mid + 1;
20         else right = mid - 1;
21     }
22     return -1;
23 }