c - C 中的二进制搜索

标签 c binary-search

我实现了列表元素的搜索功能,它是二分搜索返回找到的元素的索引。我的好奇心是有一种二进制搜索方法,您可以打印列表中出现的所有元素。

下面是代码

int Binary_Search(int *array, int chave , int N) {
    int inf = 0; 
    int sup = N-1; 
    int meio;
    while (inf <= sup) {
        meio = inf + (sup-inf)/2;
        if (chave == array[meio])
            return meio;
        else if (chave < array[meio])
            sup = meio-1;
        else
            inf = meio+1;
    }

    return -1;   
}

其他来源的一部分

我怎样才能让这个代码片段只打印重复的事件?

else {
    Imprime_Struct(Tabinvertida_Fornecedor[aux]->info);
    aux=aux+1;
    while (aux != i) {
        if (strcmp(chave, TabName[aux]->info.name)==0)
            Print_Struct(TabName[aux]->info);
        aux++;
    }
}

最佳答案

您可以通过两种方式实现二分查找:

1) so that it finds the first element not smaller than given
2) so that it finds the last element not greater than given

结合使用这两种实现,您可以轻松确定每个元素的副本数。

如果您的数组仅包含整数,则您不必同时使用两者 - 只需选择一个并搜索

1) n and n+1
2) n-1 and n

分别。

这给了你对数复杂度。

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

相关文章:

java - 为什么此二进制搜索代码在Eclipse IDE上给出错误的输出?

javascript - 数组上的JS二进制搜索中的递归与无递归

c++ - 如何从主类中调用 C++ 中的函数?

c - 为什么指针中包含的内存地址和指针的地址相同?

c - 解引用链表中的错误-不是typedef错误

c - 什么是用c写的windows系统调用?

c - sqlcxt() 中的段错误

c++ - 二进制搜索 - 代码编译和运行后不显示输出

java - 默认的Java util binary-search返回错误的结果

c++ - std::vector 中的二进制搜索