program to search the elements through Binary search ( Binear search)


//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.


Related Links :

No comments:

Post a Comment


If you face any Problem in viewing code such as Incomplete "For Loops" or "Incorrect greater than or smaller" than equal to signs then please collect from My Web Site CLICK HERE


More Useful Topics...

 

History Of C..

In the beginning was Charles Babbage and his Analytical Engine, a machine
he built in 1822 that could be programmed to carry out different computations.
Move forward more than 100 years, where the U.S. government in
1942 used concepts from Babbage’s engine to create the ENIAC, the first
modern computer.
Meanwhile, over at the AT&T Bell Labs, in 1972 Dennis Ritchie was working
with two languages: B (for Bell) and BCPL (Basic Combined Programming
Language). Inspired by Pascal, Mr. Ritchie developed the C programming
language.

My 1st Program...


#include
#include
void main ()
{
clrscr ();
printf ("\n\n\n\n");
printf ("\t\t\t*******Pankaj *******\n");
printf ("\t\t\t********************************\n");
printf ("\t\t\t\"Life is Good...\"\n");
printf ("\t\t\t********************************");
getch ();
}

Next Step...


#include
#include

void main ()
{
clrscr ();
printf ("\n\n\n\n\n\n\n\n");
printf ("\t\t\t --------------------------- \n\n");

printf ("\t\t\t | IGCT, Info Computers, INDIA | \n\n");
printf ("\t\t\t --------------------------- ");

getch ();

}

Hits!!!