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/

相关文章:

binary-search - 二分查找中间值计算

使用c递归创建线程

c - 在文字和标识符之外不允许使用非 ASCII 字符(C 编程)

c - 使用 GDB 找出我的 C 程序挂起的位置?

c - sem_open 是否分配内存?

c++ - 二分查找的使用

python - 二进制搜索中的无限循环

C 创建用户指定的文件和文件夹

c# - 对多维数组中的第一个元素进行二进制搜索

javascript - 二分查找提前退出?