Binary search with recursion
Binary Search With Recursion Using C program
Program:
#include<stdio.h>
void main()
{
   int a[50],n,i,key,f;
   clrscr();
   printf("enter no of elements to be entered");
   scanf("%d",&n);
   printf("enter elements ");
   for(i=1;i<=n;i++)
      scanf("%d",&a[i]);
   printf("enter the key to search");
   scanf("%d",&key);
   f=bsearch(a,n,key);
   if(f==0)
      printf("the key not found");
   else
      printf("the %d is found at %d",key,f);
   getch();
}
int bsearch(int a[],int n,int key)
{
   int low=1,high=n,mid;
   while(low<=high)
   {
      mid=(low+high)/2;
      if(key==a[mid])
          return mid;
      else if(key>a[mid])
          low=mid+1;
      else
          high=mid+1;
    }
    return 0;
}
Output:
 
 
 
 
          
      
 
  
 
 
 
 
 
 
 
 
 
 
No comments:
Post a Comment