折半查找

/*应用条件:只用于有序数组*/
/*当然,还可以从前往后依次查找,不过比较慢*/
/*在题目有时间限制时,用二分查找法(折半查找)比较好*/
#include<stdio.h>
int mid_seek(int a[], int n, int m)
{
    int low = 0, high = n-1, mid;
    while(low <= high)
    {
        mid = (low + high)/2;
        if(m < a[mid])
            high = mid - 1;     /*在mid的左侧*/
        else if(m > a[mid])
            low = mid + 1;
        else if(m == a[mid])
            return mid;
    }
    return -1;

}
int main()
{
    int n;
    while(scanf("%d",&n) != EOF)
    {
        int i, a[100], m;           /*m 表示要查找的数*/
        for(i = 0; i < n ;i++)
            scanf("%d",&a[i]);
        scanf("%d",&m);
        int location = mid_seek(a, n, m);
        if(location == -1 )
            printf("NOT FOUND\n");
        else
            printf("The location of %d is %d\n", m, location );
    }
    return 0;
}

 

posted @ 2019-01-28 10:13  DIY-Z  阅读(164)  评论(0编辑  收藏  举报