// Program to search an element from an array using BINARY SEARCH
#include
#include
int bsearch(int [],int,int);
int main()
{ int AR[50],ITEM,N,index;
clrscr();
cout<<"ENTER DESIRED ARRAY SIZE(MAX 50): " ;
cin>>N;
cout<<"\n ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)\n";
for(int i=0;i cin>>AR[i];
cout<<"\n ENTER ELEMENTS TO BE SEARCHED FOR:";
cin>>ITEM;
index=Bsearch(AR,N,ITEM);
if(index==-1)
cout<<"\n SORRY!!! GIVEN DATA CAN'T BE OPENED \n";
else
cout<<"\n ELEMENTS FOUND AT INDEX:"< <<"\t,Position:"< return 0; }
int bsearch(int AR[],int size ,int item)
{ int beg ,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{ mid=(beg+last)/2;
if(item==AR[mid])
return mid;
else if(item>AR[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
===================:OUTPUT:===============================================
ENTER DESIRED ARRAY SIZE(MAX 50): 4
ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)
4
25
60
78
ENTER ELEMENTS TO BE SEARCHED FOR: 78
ELEMENTS FOUND AT INDEX:3 , POSITION:4
#include
#include
int bsearch(int [],int,int);
int main()
{ int AR[50],ITEM,N,index;
clrscr();
cout<<"ENTER DESIRED ARRAY SIZE(MAX 50): " ;
cin>>N;
cout<<"\n ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)\n";
for(int i=0;i cin>>AR[i];
cout<<"\n ENTER ELEMENTS TO BE SEARCHED FOR:";
cin>>ITEM;
index=Bsearch(AR,N,ITEM);
if(index==-1)
cout<<"\n SORRY!!! GIVEN DATA CAN'T BE OPENED \n";
else
cout<<"\n ELEMENTS FOUND AT INDEX:"< <<"\t,Position:"< return 0; }
int bsearch(int AR[],int size ,int item)
{ int beg ,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{ mid=(beg+last)/2;
if(item==AR[mid])
return mid;
else if(item>AR[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
===================:OUTPUT:===============================================
ENTER DESIRED ARRAY SIZE(MAX 50): 4
ENTER ARRAY ELEMENTS(MUST BE STORED IN ASC ORDER)
4
25
60
78
ENTER ELEMENTS TO BE SEARCHED FOR: 78
ELEMENTS FOUND AT INDEX:3 , POSITION:4
No comments:
Post a Comment