Tuesday, October 4, 2011

Data Structure Lab Programs - recursion concept write program for finding the element in the array using Binary Search Method.

Practical # 2

 

/* Using recursion concept write program for finding the element in the array using Binary Search Method. */

 

#include<stdio.h>

#include<conio.h>

void main()

{

int x[10],n,i,e,found;

clrscr();

printf("Enter total no's of element=");

scanf("%d",&n);

if(n>10)

{

printf("OVERFLOW");

}

else

{

printf("The elements are=");

for(i=0;i<n;i++)

{

scanf("%d",&x[i]);

}

}

printf("Enter item to be searched=");

scanf("%d",&e);

found=binary_search(x,e,0,n-1);

if(found==-1)

{

printf("Item not found");

}

else

{

printf("Item found at location=%d",found+1);

}

getch();

}

binary_search(int x[],int e,int begin,int end)

{

int mid;

if(begin>end)

return -1;

mid=(begin+end)/2;

if(x[mid]==e)

return mid;

else if(e>x[mid])

binary_search(x,e,mid+1,end);

else

binary_search(x,e,begin,mid-1);

}

 

Output :-

 

Enter total no's of element=6

The elements are=2

5

7

9

12

34

Enter item to be searched=12

Item found at location=5

 

 

 

 

No comments :

Post a Comment