折半查找

#include <stdio.h>
#define N 10  //N表示数组元素的个数是10

int main()
{
    int array[N]={100,1,40,29,45,22,98,2,83,75};

    int find=83;
    int idx=-1;

    int left=0;
    int right=sizeof(array)/sizeof(array[0])-1;

    while(left<=right)//等号也是一种判断条件
    {
        int mid=(left+right)/2;

        if(find==array[mid])
        {
            idx=mid;
            break;
        }

        if(find>array[mid])
        {
            left=mid+1;
        }
        else
        {
            right=mid-1;
        }

    }

    if(idx==-1)
    {
        printf("find none in array\n");
    }
    else
        printf("the find idx in array=%d\n",idx);

    return 0;
}

打印结果:

 

posted @ 2018-08-21 16:35  OneMusk  阅读(126)  评论(0编辑  收藏  举报