二分查找 简易版
二分查找 简易版
参考 K&R C
#include <stdio.h> //binsearch函数: 在v[0..n-1]中查找x,其中v[i]<=v[i+1] //若找到返回下标(0-base),若找不到返回-1; int binsearch(int v[], int x, int low,int high){ int mid; while(low<=high){ mid=(low+high)/2; if(v[mid]==x){ return mid; } else if(v[mid]>x){ high=mid-1; } else if(v[mid]<x){ low=mid+1; } } return -1; } int main(){ int v[]={1,2,3,4,5,6,7,8}; int x; while(1){ scanf("%d",&x); if(x==100) break; else printf("the index of x is %d\n",binsearch(v,x,0,7)); } printf("break while\n"); getchar(); return 0; }
运行结果