//?二分法查找算法
成都創(chuàng)新互聯(lián)公司成都網(wǎng)站建設(shè)按需求定制開發(fā),是成都網(wǎng)站維護公司,為塑料袋提供網(wǎng)站建設(shè)服務(wù),有成熟的網(wǎng)站定制合作流程,提供網(wǎng)站定制設(shè)計服務(wù):原型圖制作、網(wǎng)站創(chuàng)意設(shè)計、前端HTML5制作、后臺程序開發(fā)等。成都網(wǎng)站設(shè)計熱線:028-86922220
int?binary_search(int?arr[],int?*top,int?*bot,int?x){
if?(*bot?=?*top){
int?index=?*top?+?(*bot?-?*top)?/?2;
int?*mid?=?index;
if?(arr[*mid]?==?x)?return?*mid;
if?(arr[*mid]??x)?{?//?x在左側(cè)
*mid?=?*mid?-?1;
return?binary_search(arr,?top,?mid,?x);
}
else{?//?x在右側(cè)
*mid?=?*mid+1;
return?binary_search(arr,?mid,?bot,?x);
}
}
return?-1;
}
void?main()
{
int?a[10]?=?{?1,?3,?5,?7,?8,?9,?12,?13,?15,?17?};
int?n?=?sizeof(a)?/?sizeof(a[0]),?x?=?13,?t?=?0;
int?*top?=?t,?*bot?=?n;
*bot?=?*bot?-?1;
int?index?=?binary_search(a,?top,?bot,?x);
if?(index?=?0){
printf("%d在數(shù)組索引為[%d]的位置\n",?x,?index);
}
else{
printf("%d在數(shù)組中不存在!\n",?x);
}
}
//參考代碼如下:
#include stdio.h
int main()
{
int i, j, n, k=0, isFound=0;
int num[15] = {88,86,75,74,61,56,52,43,39,34,31,22,18,16,8}; //測試數(shù)組
printf("請輸出一個整數(shù):\n");
scanf("%d", n);
i = (int)15/2; //對折位移量
j = (int)15/2; //取數(shù)“指針”
while(k2)
{
i = (int)i/2;
if(i == 0) k++; //i==0 即折半到無可再折時,仍有最后一次比較,故以k做計數(shù)
//若未相等,計算下一循環(huán)指針的位置
if(nnum[j])
j = j + (i + 1);
else if(nnum[j])
j = j - (i + 1);
else
{
isFound = 1;
break; //若找到相等數(shù),標記已找到并退出循環(huán)
}
}
//輸出結(jié)果
if(isFound)
printf("該數(shù)是數(shù)組中第%d個元素的值\n", j);
else
printf("查無此數(shù)!\n");
return 0;
}
#includestdio.h
int find(int a[],int x,int n,int m)
{int i;
if(nm)return -1;
i=(n+m)/2;
if(a[i]==x)return i;
if(a[i]x)return find(a,x,n,i-1);
return find(a,x,i+1,m);
}
int main()
{
int a[20]={2,3,6,7,12,18,19,21,25,28,30,33,37,39,42,45,47,49,50,51};
int x,i;
printf("已有的數(shù)是:\n");
for(i=0;i20;i++)
printf("%d ",a[i]);
printf("\n請輸入要查找的數(shù):");
scanf("%d",x);
if((i=find(a,x,0,19))=0)
printf("%d是第%d個數(shù)\n",x,i+1);
else printf("未找到%d\n",x);
return 0;
}
#include?stdio.h
int?look_up(int?a[],int?n,int?x)
{
int?left=0,right=n-1,mid;
while(left=right)
{
mid=(left+right)/2;
if(x==a[mid])
return?mid+1;??//加一后才是它的邏輯位序?
else?if(xa[mid])
right=mid-1;
else
left=mid+1;
}
if(leftright)
return?-1;
}
int?main()
{
int?a[100],n,x,i,result;
scanf("%d",n);
for(i=0;in-1;i++)
scanf("%d,",a[i]);
scanf("%d",a[i]);
scanf("%d",x);
result=look_up(a,n,x);
if(result=0)
printf("%d\n",result);
else
printf("No\n");
}
/*折半查找遞歸函數(shù),如果查找成功,函數(shù)返回關(guān)鍵字所在位置,否則返回-1*/
/* s為有序數(shù)列,a、b分別為查找區(qū)間的起點和終點,key為查找關(guān)鍵字 */
int half(int s[],int a,int b,int key)
{
int mid;
if(a==b)
if(key==s[a]) return (a);
else return (-1);
else
{
mid=(a+b)/2;
if(keys[mid]) return(half(s,a,mid,key));
if(keys[mid]) return(half(s,mid+1,b,key));
if(key==s[mid]) return (mid);
}
}
這是折半查找的遞歸算法,應(yīng)該是你說的意思??!