intsearch(int key,int a[],int length){ int left=0; int right=length-1; int sem = -1; //设置变量判断 while (right > left){ int x = (left + right)/2; //x为数组中间的值(mid) if (a[x]==key){ sem = 1; }elseif (a[x]<key){ left = x + 1; } else { right = x - 1; //二分法分 } }return sem; } intmain(){ int a[]={0,6,7,9,15,36,99,445,236}; int key; scanf("%d",&key); int length = sizeof(a)/sizeof(a[0]); int sem = search(key,a,length); if (sem == 1){ printf("%d在数组中\n",key); }else { printf("%d不在数组中\n",key); }return0; }
#include<stdio.h> intsearch(int key,int *a,int length){ int left=0; int right=length-1; int sem = -1; //设置变量判断 while (right >= left){ int x = (left + right)/2 ; //x为数组中间的值(mid) if (a[x]==key){ sem = 1; break; }elseif (a[x]<key){ left = x + 1; } else { right = x - 1; //二分法分 } }return sem; } intmain(){ int a[]={0,6,7,9,15,36,99,445,536}; int key; scanf("%d",&key); int length = sizeof(a)/sizeof(a[0]); int sem = search(key,a,length); if (sem == 1){ printf("%d在数组中\n",key); }else { printf("%d不在数组中\n",key); }return0; }