【问题标题】:Recursive Binary Search Program C递归二分查找程序 C
【发布时间】:2020-08-05 15:36:33
【问题描述】:

如果密钥小于等于 11,则以下代码可以正常工作,但如果密钥大于 11,则它不会返回任何内容。

#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;
}
    

上述代码的输出如下:

【问题讨论】:

    标签: c recursion binary-search


    【解决方案1】:

    int mid = (h-l)/2; 肯定是错误的。 mid 应该是 (h + l)/2

    【讨论】:

    • 我在发布问题后才发现错误。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2012-12-19
    • 2020-11-13
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多