cbsearch

Bsearch function in C not working properly


Basically I'm creating a program that will output the number if it is found in an given array or output -1 if not found. (Sorted Array.)

#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;
}

INPUT : 10

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

OUTPUT : -1 1 2 3 4 -1 6 -1 -1 9

My OUTPUT : -1 -1 -1 3 4 -1 -1 -1 -1 -1


Solution

  • 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.

    The whole point of binary searching is that if the array has size size you start in position size/2. If this element is less than what you're looking for, then go to size/2 + size/4, and otherwise go to size/2 - size/4. If this approach should work, the array needs to be sorted.

    Read more about binary searching here: https://en.wikipedia.org/wiki/Binary_search_algorithm

    And as mentioned in comments, scanf("%d",a+i) is correct, but scanf("%d",&a[i]) is preferable.