二分查找

二分查找就是折半查找,其基本思想是,首先选取表中间位置的记录,将其关键字与给定关键字key进行比较,若相等,则查找成功,若key值比该关键值大则要找的元素一定在右子表中,则继续对右子表进行折半查找,若key值比该关键值小,则要找的元素一定在左子表中,继续对左子表进行折半查找

#include <stdio.h>

void binary_search(int key,int a[],int n)
{
        int low,high,mid,count=0;
        low = 0;
        high = n;
        while(low < high)
        {
                if(count > 100){
                        printf("max counts!");
                        break;
                }
                count++;
                mid = (low + high)/2;
                if(key < a[mid]){
                         high = mid - 1;
                }
                if(key > a[mid]) {
                        low = mid + 1;
                }
                if(key == a[mid]){
                        printf("%d",count);
                        break;
                }
        }
}

int main(void)
{
        int i,a[100];
        for(i=0;i<100;i++)
        {
                a[i] = i;
        }
        scanf("%d",&i);
        binary_search(i,a,100);
        return 0;
}