0% found this document useful (0 votes)
15 views2 pages

Binary Search

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

Binary Search

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Q2.

BINARY SEARCH (RECURSIVE)


//program for binary search
#include<stdio.h>
#include<conio.h>
//function for binary search recursive
int b_search(int key,int a[],int l,int h)
{
int mid;
l=0;
h=n-1;
if(l<=h)
{
mid=(l+h)/2;

if(key==a[mid])
{
return mid;
}
else if(key>a[mid])
{
b_search(key,a,mid+1,h);
}
else
{
b_search(key,a,l,mid-1);
}
}
return -1;
}
void main()
{
int a[50],i,n,key,h,l,position;
clrscr();
printf("\nenter the number of element in array");
scanf("%d",&n);
printf("enter the array element(sorted):");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the element to be search:");
scanf("%d",&key);

position=b_search(key,a,l,h);
if(position==-1)
{
printf("element is not present in given array");
}
else
{
printf("%d is present at %d position",key,position+1);
}
getch();
}

Output :

You might also like