close
#include<stdio.h>

int binary_search(int list[], int left, int right, int key);


int main(void)
{

int left,right,mid,key;

int found=0;// -1:not found

int num[]={5,12,34,56,76,81,99,123,145,168};


printf("Please input a int:\n");

scanf("%d",&key);


left=0;

right=9;

found=binary_search(num,left,right,key);

if(found>=0){

printf("The Key:%d is at Position:%d\n",key,found);

}else{

printf("Data not Found\n");

}

return 0;
}


int binary_search(int list[], int left, int right, int key)
{

int mid=(left+right)/2;

if(left<=right)

{

if(key==list[mid])

return(mid);

else if(key>list[mid])

return(binary_search(list,mid+1,right,key));

else

return(binary_search(list,left,mid-1,key));

}else

return(-1);

}


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 GavinHuang 的頭像
    GavinHuang

    Gavin的部落格

    GavinHuang 發表在 痞客邦 留言(0) 人氣()