My Profile

I, Das ShrikKrishna J. MCA III IMSCD&R, Ahmednagar.

Monday, 15 August 2011

Search an Element using Binary Search (Recursive)

Write a Program in C to Search an Element in the Array using Binary Search (Recursive)
#include<stdio.h>
#include<conio.h>
int a[10],flag=0;
int binary(int num,int start, int mid, int end)
{
if(start<=end)
{
if(a[mid]==num)
{
flag=1;
mid++;
return mid;
}
else
{
if(num>a[mid])
{
start=mid+1;
}
else
{
end=mid-1;
}
mid=(start+end)/2;
binary(num,start,mid,end);
}
}
mid++;
return mid;
}
void main()
{
int i,start,end,mid,num,ans;
clrscr();
printf("Enter 5 Numbers\n");
for(i=0;i<=4;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched : ");
scanf("%d",&num);
start=0;
end=4;
mid=(start+end)/2;
ans=binary(num,start,mid,end);
ans++;
if(flag==1)
{
printf("Number (%d) found at position (%d)",num,ans);
}
else
{
printf("Didnot find the number (%d)",num);
}
getch();
}

No comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | cheap international calls