如果二进制搜索的数字不在索引中,如何返回NULL?

时间:2019-01-31 03:52:51

标签: c algorithm pointers search binary

我正在编写代码,基本上完成了一个主要问题。我已经编写了一个二进制搜索功能,返回找到的索引。每当我运行代码并搜索2的任意幂时,它便可以正常工作。但是,每当我输入其他任何数字(例如50)时,它都会返回错误。

在代码的末尾,我有一条else语句,该语句表明其他语句是否都没有返回值来返回NULL,所以我有点麻烦。谢谢。我在Xcode以及UNIX服务器上运行,但是我注释掉了在UNIX服务器上运行的行。

#include <stdio.h>
#include <stdlib.h>
    int* search(int* begin, int* end, int needle);
    int main(int argc, char **argv) { //int argc = 1, char **argv array of char pointers
        int num = 0;
        int nums[10], i;
        int *found = NULL;
        if(argc != 2) {
            printf("Enter a number to a power of 2 to search for:\n");
            scanf("%d" , &num);
        }
       // num = atoi(argv[1]);
        for(i = 0; i < 10; i++) { // initialzes array by shifting binary code to the left adding powers of 2
            nums[i] = 1 << i; }
        found = search(nums, &nums[9], num);
        if(found) {
            printf("Number %d found in index %ld.\n", num, found - nums);
                 }
        else {
            printf("Number %d was not found.\n", num);
       }
        return 0;
    }
int* search(int* begin, int* end, int needle){
    int *middle = (end-begin)/2 + begin;
    if(*middle == needle){
        return middle;
    }
    else if(needle < *middle){
        end = middle;
        return search(begin, end-1, needle);
    }
    else if(needle > *middle)
    {
        begin = middle;
        return search(begin+1, end, needle);
    }
    else
        return NULL;
}

我希望main()函数中的else语句只要搜索到的值不在索引中就执行。

1 个答案:

答案 0 :(得分:1)

您的问题是您的递归没有基础

这样想:如果数字不在数组中,您的针将始终大于或小于中间针

这意味着它永远不会到达最后,它总是会递归递增或递减,直到尝试取消引用乱码,从而导致分段错误

您需要的是将旧的基本案例添加到二进制搜索中,如下所示:

int* search(int* begin, int* end, int needle) {
    int *middle = (end-begin)/2 + begin;

    if(begin == end) {
        //recursion ends when there are no more segments to divide in two
        //so after your final single element segment, a decrement or increment will happen
        //making your end and begin pointers the same 
        return NULL;
    }
    else if(*middle == needle) {
        return middle;
    }
    else if(needle < *middle) {
        end = middle;
        return search(begin, end-1, needle);
    }
    else if(needle > *middle) {
        begin = middle;
        return search(begin+1, end, needle);
    }   
}