How would you use bsearch()function to search a name stored in array of pointers to string?

How would you use bsearch()function to search a name stored in array of pointers to string?

bsearch, It is a library function.Using this we done data entry in array. Ther is mandatry in binary search your must sorted in ascending order.And do compare two datas.For using this function we have to include stdlib.h library function.

Syntax:

void *bsearch(void *key, void *base, size num, size width,
int (*cmp)(void *emt1, void *emt2));

where;
emt->Element.

Some steps that we have to follow when we using 
bsearch.

1. It is passed pointers to two data items
2. It returns a type int as follows:
   2.1) <0 Element 1 is less than element 2.
   2.2) 0 Element 1 is equal to element 2.
   2.3) > 0 Element 1 is greater than element 2. 
example:

#include 
#include 
#include 
#define TABSIZE    1000

struct node { /* These are stored in the table. */
   char *string;
   int length;
};
struct node table[TABSIZE];/*Table to be search*/
    .
    .
    .
{
    struct node *node_ptr, node;
    /* Routine to compare 2 nodes. */
    int node_compare(const void *, const void *);
    char str_space[20];   /* Space to read string into. */
    .
    .
    .
  node.string = str_space;
  while (scanf("%s", node.string) != EOF) {
         node_ptr = (struct node *)bsearch((void *)(&node),(void *)table, TABSIZE,sizeof(struct node), node_compare);
  if (node_ptr != NULL) 
  {
     (void)printf("string = %20s, length = %d\n",
             node_ptr->string, node_ptr->length);
  } 
  else 
  {
     (void)printf("not found: %s\n", node.string);
  }
}
}
/*
    This routine compare two nodes based on an
    alphabetical ordering of the string field.
*/
int node_compare(const void *node1, const void *node2)
{
   return strcoll(((const struct node *)node1)->string,((const struct node *)node2)->string);
}


By:Vivek Kr. Agarwal
Date:2002-01-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related C Subjective Links

C Subjective interview questions and answers for experienced and fresher