c - 这个二进制搜索函数有什么问题?

标签 c binary-search

我正在尝试解决二进制搜索的 Spoj 问题,但我一直得到“错误答案”,而且我看不到我的问题。 这是我的 bsearch 函数:

int binarySearch(int numbers[], int size, int key)
{
    int start = 0;
    int end = size - 1;
    int middle;

    while(start <= end)
    {
        middle = start + (end - start)/2;

        if(key < numbers[middle])
            end = middle - 1;
        else if(key > numbers[middle])
            start = middle + 1;
        else
            return middle;
    }

    return -1;
}

这是我的主要功能

int main()
{
    int *numbers;
    int n_numbers, n_queries, key, i, found;

    scanf("%d %d", &n_numbers, &n_queries);
    numbers = (int*)malloc(n_numbers * sizeof(int));

    for(i = 0; i<n_numbers; i++)
        scanf("%d", &numbers[i]);

    for(i = 0; i<n_queries; i++)
    {
        scanf("%d", &key);
        found = binarySearch(numbers, n_numbers, key);
        printf("%d\n", found);
    }

    return 0;
}

这是 SPOJ 问题: http://www.spoj.com/problems/BSEARCH1/

最佳答案

问题是您需要返回第一次出现的位置(从零开始),并且您会在找到 key 后立即返回。

但数组可能是: 0 1 1 1 1 1 1 1 1 1 1 1 2

关键是 1。您应该返回 1(第一次出现的位置),而不是返回 6。

关于c - 这个二进制搜索函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13922893/

相关文章:

c - UTF-8 解码器在处理非 ASCII 字符时失败

java - indexOf 还是二进制搜索?

mysql - 排序关系中记录的索引

c++ - C和C++中枚举的用途是什么

c - 使用 execve() 执行反向 shell

c - C 中的链表搜索/插入

java - 通过二分查找递归帮助(Java)

c - C中sizeof的简单实现

python - 查找数组中缺失的元素

search - 搜索字符串算法