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
The C library function void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) function searches an array of nitems objects, the initial member of which is pointed to by base, for a member that matches the object pointed to, by key. The size of each member of the array is specified by size.
The contents of the array should be in ascending sorted order according to the comparison function referenced by compar.
二进制搜索的要点在于,如果数组的大小为 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])
更可取。
基本上,我正在创建一个程序,如果在给定数组中找到该数字,则输出该数字;如果未找到,则输出 -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
The C library function void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) function searches an array of nitems objects, the initial member of which is pointed to by base, for a member that matches the object pointed to, by key. The size of each member of the array is specified by size.
The contents of the array should be in ascending sorted order according to the comparison function referenced by compar.
二进制搜索的要点在于,如果数组的大小为 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])
更可取。