第七章例7-6

/* 二分查找法 */
#include<stdio.h>
int main(void)
{
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    int low,high,mid,n=10,x;

    printf("Enter x:");
    scanf_s("%d",&x);
    low=0;high=n-1;
    while(low<=high)  {
        mid=(low+high)/2;
        if(x==a[mid])
            break;
        else if(x<a[mid])
            high=mid-1;
        else
            low=mid+1;
    }
    if(low<=high)
        printf("Index is %d\n",mid);
    else
        printf("Not Found\n");
    return 0;
}

 

posted @ 2013-10-06 21:23  刘睿1994  阅读(87)  评论(0编辑  收藏  举报