折半查找法

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 15
int main() {

    int a[N]={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29};
    int flag=1,sign=0,local=0,top=0,bott=N-1,mid;
//sign标记是否找到。local标记下标。top bott表示查找范围。
    int number=0;
    printf("input a number:");
    scanf("%d",&number);
    while(flag){
        if(number<a[0]||number>a[N-1])
            local=-1;

        while(!sign&&top<=bott){
                mid=(top+bott)/2;
                if(number==a[mid]){
                    local=mid;
                    printf("find the number,position is %d",mid+1);
                    sign=1;
                    flag=0;
                }
                else if(number<a[mid]){
                    bott=mid-1;
                }else {
                    top=mid+1;
                }

        }


                if(!sign||local==-1){
                    printf("cannot find %d.\n",number);
                    flag=0;
                }
    }


}
posted @ 2024-04-30 15:22  zhongta  阅读(26)  评论(0)    收藏  举报