繁体   English   中英

C 中的 Bsearch 功能无法正常工作

[英]Bsearch function in C not working properly

基本上我正在创建一个程序,如果在给定的数组中找到它就会输出数字,如果没有找到则输出 -1。 (排序数组。)

#include <stdio.h>
#include <stdlib.h>

int cmp(const void*a,const void *b){
    if(*(int*)a-*(int*)b>0) return 1;
    if(*(int*)a-*(int*)b<0) return -1;
    return 0;
}

int main() {
    int n; scanf("%d",&n);
    int a[n];

    for(int i =0;i<n;i++) 
        scanf("%d",a+i);

    for(int i =0;i<n;i++){
        int *item;
        item = (int*)bsearch(&i,a,n,sizeof(int),cmp);
        if(item!=NULL) printf("%d ",i);
        else printf("-1 "); 
    }

    return 0;
}

输入: 10

-1 -1 6 1 9 3 2 -1 4 -1

输出: -1 1 2 3 4 -1 6 -1 -1 9

我的输出: -1 -1 -1 3 4 -1 -1 -1 -1 -1

https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm

C 库函数 void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) 函数搜索 nitems 对象数组,初始成员其中由 base 指向,用于匹配 key 指向的对象的成员。 数组每个成员的大小由大小指定。

数组的内容应该根据compar引用的比较函数按升序排列

二分查找的全部意义在于,如果数组具有 size size ,则从位置size/2 如果此元素小于您要查找的元素,则转到size/2 + size/4 ,否则转到size/2 - size/4 如果这种方法可行,则需要对数组进行排序。

在此处阅读有关二进制搜索的更多信息: https : //en.wikipedia.org/wiki/Binary_search_algorithm

正如评论中提到的, scanf("%d",a+i)是正确的,但scanf("%d",&a[i])更可取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM