我的二进制搜索程序可以编译,但我的算法有问题。例如,如果我试图在列表2 5 7 8 9 10中找到9,我的程序会说列表中没有9。我哪里做错了?

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int valuetofind, n, list [100];
bool found, notinthelist;

int binary_search () {
    int middle, p = 0, q = n-1;

    middle = (p + q) / 2;
    while ( (found == false) && (notinthelist == false) ) {
        if (list[middle] == valuetofind) {
            found = true;
            printf("%d is the %d element\n", valuetofind, middle+1);
        }
        else {
            if (n < list[middle] )  q = middle - 1;
            else p = middle + 1;

            if (p > q) {
                notinthelist = true;
                printf("%d is not in this list\n", valuetofind);
            }
        }
        middle = (p + q) / 2;
    }
}

int main () {
    found = false;
    notinthelist = false;
    printf("How many elements are there in your list?\n");
    scanf("%d", &n);
    for (int i = 0; i<n; i++){
      scanf("%d", &list[i]);
    }
    printf("What value do you want to find?\n");
    scanf("%d", &valuetofind);
    binary_search();
}

最佳答案

变化

if (n < list[middle] )  q = middle - 1;


if (valuetofind < list[middle] )  q = middle - 1;

关于c - C二进制搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33553521/

10-12 17:32