1. 程式人生 > >二分查詢訓練1

二分查詢訓練1

問題及程式碼:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

int main()
{
    int d[SIZE]= {1,2,4,6,8,10,12,14,32,64};
    int key,index=-1,low,high,mid;
    printf("please input the key:");
    scanf("%d",&key);
    low=0,high=SIZE-1;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(d[mid]==key)
        {
            index=mid;
            break;
        }
        else if(d[mid]>key)
        {
            high=mid-1;
        }
        else
        {
            low=mid+1;
        }
    }
    if(index>=0)
    {
        printf("find it\n");
    }
    else
    {
        printf("no find\n");
    }
    return 0;
}