折半查找

/*本程序采用折半查找算法查找数据的位置     2013.12.06.18:11 */
#include <stdio.h>
int search(int a[],int l,int o)//实现折半查找
{
    int mid;
    int high=l-1;//notice
    int low=0;
    do
    {
    mid=(low+high)/2;
    if (a[mid]==o)//notice
    return mid+1;
    else if (o>a[mid])//notice
    low=mid+1;
    else
    high=mid-1;
    }
    while(low<=high);//notice!!!
    return -1;
   
}
int main(int argc,char **argv)
{
    int n[8] ={2,4,8,10,12,14,15,17};//要求数据元素必须有序
    int i=0;
    int result;
    int input;
    printf(" 所有数据如下,请输入要查找的数据,本程序将列出它的位置  采用折半查找算法 ");
    while(i<8)
    {
        printf("%d    ",n[i]);
        i++;
    }
    puts(" ");
    scanf("%d",&input);
    result=search(n,8,input);
    if (result==-1)
    printf("输入有误,请检查!");
    else
    printf("您查找的数据  %d在  %d处 ",input,result);
    return 0;
}

原文地址:https://www.cnblogs.com/lzh-Linux/p/3480400.html