C二进制搜索

时间:2015-11-05 19:49:38

标签: c binary-search

我的二进制搜索程序编译,但我的算法有问题。例如,如果我尝试在列表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();
}

1 个答案:

答案 0 :(得分:3)

更改

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

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