C语言:有七个数按由大到小顺序存放在一个数组中,输入一个数,要求用折半查找法

如题所述

#include<stdio.h>
#define N 7
int main(){
    int a[N]={100,90,70,50,30,10,1};
    int m,find=0;
    int left=0,right=N-1,i=(left+right)/2,l,r;
    scanf("%d",&m);
    while(!(l==left&&r==right)){//当left和right不再改变,跳出循环
        l=left;r=right; //l,r分别对应上一次循环的left和right
        if(m==a[i]){find=1;break;}
        else if(m>a[i]){right=i;i=(left+right-1)/2;}
        else{left=i;i=(left+right+1)/2;}
    }
    if(find) printf("%d is in location %d\n",m,i+1);
    else printf("%d is not in a[]\n",m);
    return 0;
}

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答