C中的二进制搜索

时间:2013-11-10 15:05:03

标签: 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++;
    }
}

3 个答案:

答案 0 :(得分:1)

您可以通过两种方式实现二进制搜索:

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

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

如果你的数组只包含integeres,那么你不需要同时使用两者 - 只需选择一个并搜索

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

分别

这会给你对数的复杂性。

答案 1 :(得分:0)

获得元素的index后,您只需scan forward and backwards检查该元素即可。由于数组是sorted,所有duplicates will be together。在所有元素相同的worst case中,此方法将采用O(n)

答案 2 :(得分:0)

您的函数假定数组按降序排序。您可以修改它以查找第一个匹配的位置(如果有),并列出所有匹配项:

void list_all_matches(const int *array, int N, int chave) {
    int meio, inf = 0, sup = N; 
    while (inf < sup) {
        meio = inf + (sup - inf) / 2;
        if (chave < array[meio])
            sup = meio;
        else
            inf = meio;
    }
    while (sup < N && array[sup] == chave)
        printf("%d\n", sup++);
}