C program to search an element in the array using bsearch() function.

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

int cfun(const void * a , const void * b)
{
  int x =  *(const int * )a;
  int y =  *(const int * )b;
  
  if(x<y)
    return -1;
  
  if(x>y)
     return 1;
     
   return 0;  

}


int main()
{
    int arr[]={10,15,17,25,36};
    int *element;
	int key;

	
    printf("Enter element to search : ");
    scanf("%d",&key);

	element = (int *) bsearch(&key,arr,5,sizeof(int),cfun);  
	
	
	 /*
	   bsearch(arg1,arg2,arg3,arg4,arg5);
	   
	   arg1 >> key add. to search
	   arg2 >> array
	   arg3 >> total no. of elements in array
	   arg4 >> sizeof elements
	   arg5 >> comparator function
	 
	 */
	
	  
	
	if(element != NULL)
	   printf("Found element in the array = %d \n",*element);
	else
	   printf("Element is NOT present in the array\n");
		
	return 0;
}
OUTPUT:

Enter element to search : 17
Found element in the array = 17

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *