Sunday, December 12, 2010

Queue using array

#include
#include
#include

#define SIZE 20

class queue
{
int a[SIZE];
int front,rear;

public:
queue();
void insert();
void delet();
void display();
};

void queue::queue()
{
front=rear=-1;
}

void queue::insert()
{
int ele;

if(front==-1)
{
cout<<"\nEnter the element to be inserted:";
cin>>ele;
front++;
a[++rear]=ele;
display();
}

else if(rear>SIZE-1)
{
cout<<"\nThe queue is full....cannot insert elements";
}

else
{
cout<<"\nEnter the element to be inserted:";
cin>>ele;
a[++rear]=ele;
display();
}

}

void queue::delet()
{
if((front==rear+1)||front==-1)
{
cout<<"\nThe queue is empty.......cannot perform deletion";
front=rear=-1;
}

else
{
cout<<"The element deleted from queue is "< front++;
display();
}
}

void queue::display()
{
int i;

if((front==rear+1)||front==-1)
{
cout<<"\nThe queue is empty.......cannot perform deletion";
front=rear=-1;
}
else
{
cout<<"\nThe queue is now\n";
for(i=front;i<=rear;i++)
{
cout< }
}
}

void main()
{
int ch;
queue q1;
clrscr();
do
{
cout<<"\n--------------Queue operations--------------";
cout<<"\n1_Insertion";
cout<<"\n2_Deletion";
cout<<"\n3_Display";
cout<<"\n4_Exit";
cout<<"\nEnter your choice<1-4>:";
cin>>ch;

switch(ch)
{
case 1:
q1.insert();
break;

case 2:
q1.delet();
break;

case 3:
q1.display();
break;

case 4:
exit(0);
break;

default:
cout<<"\nInvalid choice!!!!";
break;
}
}while(ch!=4);
getch();
}

Binary search on array

#include
#include

#define SIZE 20

class array
{
int a[SIZE];
int n;

public:
array();
void read();
void binary_search();
void display();
};

array::array()
{
n=0;
}

void array::read()
{
int i;
cout<<"\nEnter the size of the array:";
cin>>n;
cout<<"\nEnter the "< for(i=0;i {
cin>>a[i];
}
}

void array::binary_search()
{
int i,j,mid,lb,ub,flag;
int temp,item;

for(i=0;i {
for(j=i+1;j {
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"\nThe sorted array is:\n";
for(i=0;i cout<<"\t" < cout<<"\nEnter the item to be searched:";
cin>>item;



for(lb=0,ub=n-1;lb {
mid=(lb+ub)/2;
if(a[mid]==item)
{
flag=1;
break;
}
else if(item>a[mid])
{
lb=mid+1;
}
else if(item {
ub=mid-1;
}
else
{
flag=0;
}
}
if(flag==1)
{
cout<<"\n\nThe element "< }
else
{
cout<<"\nThe element is not found in array!!!!";
}
}

void array::display()
{
int i;

cout<<"\nThe array is \n";
for(i=0;i {
cout< }
}

void main()
{
array a1;

clrscr();

a1.read();
a1.display();
a1.binary_search();

getch();
}