折半查找C程序

折半查找C程序

#include #define n 51 void main(void) { int a[n]; int i,n,num; int top,bottom,mid; int flag=1; //如果在表列中找到数字,则值为1,否则为0 int loc=-1;//要查找的数在表列中的位置,如果loca=-1表示表列中没有这个数;如果有这个数,则它的值为所在的位置 printf("你想在多少个数中进行折半查找,请输入(1--50):"); scanf("%d",&n); while(n<1 || n>50) { printf("你输入的数不正确,请重新输入。

\n"); printf("你想在多少个数中进行折半查找,请输入(1--50):"); scanf("%d",&n); } printf("请你输入一个整数 a[1](需保证递增有序):"); scanf("%d",&a[1]); i=2; while(i<=n) //输入从小到大的表列 { printf("请你输入一个整数 a[%d](需保证递增有序):",i); scanf("%d",&a[i]); if(a[i] > a[i-1]) i++; else printf("你输入的数不满足要求,请重新输入。

\n"); } //输出表列 printf("\n输出表列\n"); for(i=1; i<=n; i++) { printf("%6d",a[i]); } printf("\n"); printf("请你输入要查找的数:"); scanf("%d",&num); flag=1; //假设输入的数在表列中 top=n; bottom=1; mid=(top+bottom)/2; while(flag) { //printf("top=%d, bottom=%d, mid=%d, a[%d]=%d\n",top,bottom,mid,mid,a[mid]); if( (num>a[top]) || (numa[top] 或者 numnum) //若 a[mid]>num,则num 一定在 a[bottom]和a[mid-1]范围之内 { top=mid-1; mid=(top+bottom)/2; } else if(a[mid]

首页