This blog is under construction

Monday 30 April 2012

bsearch example in C

Header file:
    stdlib.h

Synopsis:
     void *bsearch(const void *key, const void *base,
                     size_t nmemb, size_t size,
                     int (*compar)(const void *, const void *));

Description:
     It performs binary search from base[0]..base[n-1] for an element that matches *key and returns pointer to the matching element, or NULL is returned if no match is found.

Note: Elements in the array base should be in ascending order.


bsearch function C example:


  #include<stdio.h>
  #include<stdlib.h>
  #include<string.h>
  #include<errno.h>
  int compare (const void *key, const void *base) {
        return(*(int *)key - *(int *)base);
  }

  int main() {
        FILE *fp;
        void *ptr;
        char *str, data[100];
        int base[100], key, n = -1, size, i;
        fp = fopen("file.txt", "r");

        if (fp == NULL) {
                str = strerror(errno);
                perror(str);
                return;
        }

        while(!feof(fp)) {
                fgets(data, 100, fp);
                data[strlen(data) - 1] = '\0';
                n++;
                base[n] = atoi(data);
        }
        printf("Enter the key value:");
        scanf("%d", &key);
        size = sizeof(int);
        ptr = bsearch(&key, base, n, size, compare);
        if (ptr == NULL) {
                printf("Given Data Not Available\n");
        } else {
                printf("Given data %d is located at %d\n",
                        *(int *)ptr, ((int *)ptr - base)+1);
        }
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat file.txt
  100
  200
  300
  400
  500
  600
  700
  800
  900
  1000
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the key value:800
  Given data 800 is located at 8



No comments:

Post a Comment