程序要求:
使用二分法实现对输入数组字符的查找,并输入需要查找数字,返回需要查找数字在该数组的位置。若不存在则返回-1。
程序如下:
- #include <stdio.h>
- #include <string.h>
- int binserch(int x,int v[],int n);
- int main()
- {
-
- int a;
- int buf[5];
- int x;
- int c;
- int i=0;
- int result;
-
- printf("please input some num\n");
- while((c=getchar())!=EOF&&c!='\n')
- buf[i++]=c;
-
- printf("please input your want find num\n");
- x=getchar();
- result=binserch(x,buf,i+1);
- printf("result =%d\n",result);
- return 0;
- }
- int binserch(int x,int v[],int n)
- {
- int low;
- int high;
- low = 0;
- high = n-1;
- int mid;
- while(low<=high)
- {
- mid = (low+high) /2;
- if(x>v[mid])
- low=mid+1;
- else if(x<v[mid])
- high=mid-1;
- else
- return mid;
- }
- return -1;
- }
阅读(3264) | 评论(0) | 转发(0) |