C 二分查找

标签 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();
}

最佳答案

改变

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

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

关于C 二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553521/

相关文章:

我可以为 __user 参数传递一个指向 linux 内核空间的指针吗?

c - 在 C 中使用递归二进制搜索查找目标索引

java - 如何查找排序数组中大于 k 的元素数量?

Scala 比较泛型?

java - 二分查找算法的问题

c - C中的分而治之二分查找

c - 语法:函数声明中的单个语句

c - 如何在 makefile 中定义宏以启用 C 头文件中的功能?

c - C中结构内部结构的问题

c - Fork数组赋值冲突