//program to search the elements through Binear search
#include
#include
class binary
{
private:
int data[25],item,loc,r;
public:
void getdata();
void search();
void sort();
};
void binary::getdata()
{
cout<cin>>r;
cout<for(int i=0;i {
cin>>data[i];
}
}
void binary::sort()
{
int k,ptr,temp;
cout<for(k=0;k {
ptr=0;
while(ptr<=r-k)
{
if(data[ptr]>data[ptr+1])
{
temp=data[ptr];
data[ptr]=data[ptr+1];
data[ptr+1]=temp;
}
ptr++;
}
}
for(int i=0;i{
cout< }
}
void binary::search()
{
cout<cin>>item;
int beg=0,end=r;
int mid=((beg+end)/2);
while(beg<=end && data[mid]!=item)
{
if (item {
end=mid-1;
}
else
{
beg=mid+1;
}
mid=((beg+end)/2);
}
if (data[mid]==item)
{
loc=mid+1;
cout<}
else
{
loc=0;
cout<}
}
void main()
{
clrscr();
binary b;
b.getdata();
b.sort();
b.search();
getch();
}
****************Output*****************
Enter the range of an array:5
Enter the elements of an array:12 22 2 1 4
Sorting order of an arry is:1 2 4 12 22
Enter the element you want to search:4
3 Is the position of the 4
****************************************
Enter the range of an array:7
Enter the elements of an array:1 0 9 6 2 3 5
Sorting order of an arry is:0 1 2 3 5 6 9
Enter the element you want to search:13
13 is not present in an array.
No comments:
Post a Comment