递归二分查找程序 C
Recursive Binary Search Program C
如果密钥小于等于 11,则以下代码可以正常工作,但如果密钥大于 11,则它不会 return 任何内容。
#include<stdio.h>
#include<time.h>
int BinaryS(int a[],int l, int h,int key)
{
if(h >= l){
int mid = (h-l)/2;
if(a[mid] == key)
return mid;
if(a[mid] > key)
return BinaryS(a,l,mid-1,key);
return BinaryS(a,mid+1,h,key);
}
return -1;
}
int main(void)
{
int a[]={10,11,15,19,22,23,30,40,45,50};
int n;
printf("Enter the number to be searched\n");
scanf("%d",&n);
int num=10;
int clock_t,start_t,end_t,total;
start_t = clock();
int f = BinaryS(a,0,num-1,n);
end_t = clock();
total = (end_t-start_t)/CLOCKS_PER_SEC;
printf("Time taken: %d\n",total);
if(f == -1){
printf("Key not found in the array ");
}
else{
printf("Key found at: %d",f+1);
}
return 0;
}
以上代码的输出结果如下:
int mid = (h-l)/2;
肯定是错的。 mid
应该是 (h + l)/2
.
如果密钥小于等于 11,则以下代码可以正常工作,但如果密钥大于 11,则它不会 return 任何内容。
#include<stdio.h>
#include<time.h>
int BinaryS(int a[],int l, int h,int key)
{
if(h >= l){
int mid = (h-l)/2;
if(a[mid] == key)
return mid;
if(a[mid] > key)
return BinaryS(a,l,mid-1,key);
return BinaryS(a,mid+1,h,key);
}
return -1;
}
int main(void)
{
int a[]={10,11,15,19,22,23,30,40,45,50};
int n;
printf("Enter the number to be searched\n");
scanf("%d",&n);
int num=10;
int clock_t,start_t,end_t,total;
start_t = clock();
int f = BinaryS(a,0,num-1,n);
end_t = clock();
total = (end_t-start_t)/CLOCKS_PER_SEC;
printf("Time taken: %d\n",total);
if(f == -1){
printf("Key not found in the array ");
}
else{
printf("Key found at: %d",f+1);
}
return 0;
}
以上代码的输出结果如下:
int mid = (h-l)/2;
肯定是错的。 mid
应该是 (h + l)/2
.