c语言二分法

 1 #include <stdio.h>  
 2 #include <stdlib.h>  
 3   
 4 int Search(int *a,int key)  
 5 {
 6     int low=0,mid;  
 7     int high=20;  
 8     while(low<=high)  
 9     {  
10         mid=(low+high)/2;  
11         if(key==a[mid]) return mid;    //找到待查元素  
12         else if(key<a[mid]) high=mid-1;//继续在前半区查找  
13         else low=mid+1;                //在后半区查找  
14     }  
15     return 0;                          //未找到  
16 }  
17   
18 void main()  
19 {  
20     int *a,key,i;  
21     int b[10]={0};  
22     a=b;  
23     printf("请输入从大到小的10个整数:\n");  
24     for(i=1;i<=10;i++)  
25     {  
26         scanf("%d",&b[i]);  
27               
28     }  
29     printf("\n");  
30     printf("请输入你要查找的数:\n");  
31     scanf("%d",&key);  
32   
33     if(!Search(a,key)) printf("要查找的数不在目标数组中!\n");  
34     else printf("你要查找的数的序号是:%d \n",Search(a,key));  
35 }  

 

posted @ 2014-12-27 15:00  偶my耶  阅读(2240)  评论(0编辑  收藏  举报