二分查找需要注意两个问题一个是临界问题,流行的方案是左开右闭区间方式,还有一个就是当数组元素中有多个相同待查找值的应该返回第一个,下面的代码可以解决这问题,记录一下,由于最近开始用gvim编程了,请原谅我的中式英语注释。
1 /* 2 * binary search from programing perls 3 * this binary search can solve the problem of when there are same value can not return the fisrt match number 4 */ 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 9 10 /* 11 * binary search 12 * return -1 can not find the number else the position of the number 13 */ 14 15 int binary_search(int in_arr[],int n,int value) 16 { 17 int left,right,middle; 18 19 left = -1,right = n; 20 21 while(left + 1 != right) 22 { 23 middle = left + (right - left) / 2; //to prevent the overflow of the int if use middle = (right + left) / 2 24 25 if(value > in_arr[middle]) 26 { 27 left = middle; 28 } 29 else 30 {// delete one compare(but can add compare times) 31 right = middle; 32 } 33 } 34 35 if(right >= n || in_arr[right] != value) 36 { 37 right = -1; 38 } 39 40 return right; 41 } 42 43 44 int main() 45 { 46 int i,value,in_arr[10]; 47 48 memset(in_arr,0,sizeof(in_arr)); 49 50 for(i = 0; i < 10; i++) 51 { 52 scanf("%d",&in_arr[i]); 53 } 54 55 while(1) 56 { 57 printf("input the value you want to find : "); 58 59 scanf("%d",&value); 60 61 int index = binary_search(in_arr,10,value); 62 63 if(index == -1) 64 { 65 printf("can not find the value "); 66 } 67 else 68 { 69 printf("the %d at the position %d ",value,index); 70 } 71 } 72 73 return 0; 74 }