Tuesday, October 4, 2011

FW: Data Structure Lab Programs - Using iteration concept write program for finding the element in the array using Binary Search Method.

Practical # 3

 

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

 

#include<stdio.h>

#include<conio.h>

void bsearch(int x[],int item,int n)

{

int start,end,mid,f=0;

end=n-1;

start=0;

 

while(end>=start)

                {

                mid=(start+end)/2;

                if(item==x[mid])

                                {

                                printf("Item Found At Possition %d",mid+1);

                                f=1;

                                break;

                                }

                else if(item>x[mid])

                                {

                                start=mid+1;

                                }

                else

                                {

                                end=mid-1;

                                }

                }

if(f==0)

                {

                printf("Item Not Found");

                }

}

void main()

{

int x[10],i,n,item;

clrscr();

printf("Enter No. Of Element : ");

scanf("%d",&n);

printf("Enter Sorted Element :..\n");

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

                {

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

                }

printf("Enter Item To Search : ");

scanf("%d",&item);

bsearch(x,item,n);

getch();

}

 

OUTPUT :-

 

Enter No. Of Element : 6

Enter Sorted Element :..

3

6

8

9

23

34

Enter Item To Search : 9

Item Found At Possition 4

 

No comments :

Post a Comment