binarysearch c代码错误

时间:2017-09-19 10:09:10

标签: c binary

这是我的二进制代码。我想要做的是当我把一些东西(不在列表中)显示'数字不在列表中'时。但它没有运作我不知道为什么

int compare(int, int);

int binsearch(int list[], int searchnum, int left, int right);

int main() {


    int right, left, middle;
    int list[MAX_NUM] = { 1,3,5,7,9,11,13,15,17,19};

    int searchnum,count=0;
    int answer;
    right = MAX_NUM-1;
    left = 0;
    printf("n : ");
    scanf_s("%d", &searchnum);

    answer=binsearch(list, searchnum, left, right);

    if (answer == -1)
        printf("%d is not in list", searchnum);
    else    
        printf("%d", answer);

    system("pause");
    return 0;
}


int compare(int x, int y) {

    if (x< y) return -1;
    else if (x == y) return 0;
    else return 1;

}


int binsearch(int list[], int searchnum, int left, int right) {

    int middle;
    while (left <= right) {
        middle = (left + right) / 2;
        switch (compare(list[middle], searchnum)) {
        case -1: left = middle - 1;
            break;
        case 0: return middle;
        case 1: right = middle - 1;

        }
    }
    return -1;
}

2 个答案:

答案 0 :(得分:0)

您必须将case -1: left = middle - 1;更改为case -1: left = middle + 1;
像你一样,你永远不会找到一个大于中位数的数字。

答案 1 :(得分:0)

算法就像

 middle = ( left + right )/2
 if middle < searchnum 
     left = middle + 1
 else if middle > searchnum
     right = middle - 1
 else
     return 0

所以它将根据条件递归搜索更大的一半或更小的一半,因为数组已经排序