与大家共享下
- // main.c
- // 二分查找
- //
- #include <stdio.h>
- #define LEN 6
- void printArray(int a[],int l){
- for (int i=0;i<l;i++){
- printf("%d ",a[i]);}}
- int binsearch(int x,int v[],int n){
- int low,high,mid;
- low=0;
- high=n-1;
- while (low<=high) {
- mid=(low+high)/2;
- if(x<v[mid]){
- high=mid-1;
- }else if (x>v[mid]){
- low=mid+1;
- }else{
- return mid;
- }
- }
- return -1;
- }
- int main(int argc,const char *argv[]){
- int scores[ ] ={50,60,70,80,90,100};
- int r=binsearch(80,scores,6);
- printf("r=%d\n",r);
-
-
- }
复制代码
|
|