You are on page 1of 184

1.

Implemention Of Stack Using Single Linked List


Stack Definition:

In computer science, a stack is a last in, first out(LIFO) abstract data type and data structure. A stack
can have any abstract data type as an element, but is characterized by only two fundamental
operations, the push and the pop.
(or)
A collection of items in which only the most recently added item may be removed. The latest added item
is at the top. Basic operations are push and pop. Often top and is Empty are available, too. Also known
as "last-in, first-out" or LIFO.

Push:
The push operation adds to the top of the list, hiding any items already on the stack, or initializing the
stack if it is empty.

Pop:
The pop operation removes an item from the top of the list, and returns this value to the caller. A pop
either reveals previously concealed items, or results in an empty list.

Stack Applications:
1. Expression evaluation.
2. Backtracking (game playing, finding paths, exhaustive searching).
3. Memory management, run-time environment for nested language features.

Alogarithm steps:
Step 1: create a list.
i) Create a new empty node top.
ii) Read the stack element and store it in top's data area.
iii) Assign top's link part as NULL (i.e. top->link=NULL).
iv) Assign temp as top (i.e. temp=top).

Step 2: Read next stack operation.


i) If it is Create then go to step1.
ii) If it is Push then it process following steps
a) Check Main memory for node creation.
b) Create a new node top.
c) Read the stack element and store it in top's data area.
d) Assign top's link part as temp (i.e. top->link=temp).
e) Assign temp as top (i.e. temp=top).
iii) If it is pop then it process following steps
a) If top is NULL then display stack is empty.
b) Otherwise assign top as temp (i.e. top=temp, bring the top to top position)
c) Assign temp as temp's link. (i.e. temp=temp->link, bring the temp to top's previous position).
d) Delete top from memory.
iv) If it is traverse then process the following steps
a) Bring the top to stack’s top position(i.e. top=temp)
b) Repeat until top becomes NULL
i) Display the top's data.
ii) Assign top as top's link (top=top->link).
C Program To Implement Stack Data Structure Using Single Linked List:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
/* Node decleration */
struct node
{
int data;
struct node *link; //to maintain the link other nodes
};
struct node *top,*temp;

void create();
void push();
void pop();
void display();
/* create function create the head node */
void create()
{
printf("\nENTER THE FIRST ELEMENT: ");
top=(struct node *)malloc(sizeof(struct node));
scanf("%d",&top->data);
top->link=NULL;
temp=top;
}

/* display function visit the linked list from top to end */


void display()
{
top=temp; // bring the top to top position
printf("\n");
while(top!=NULL)
{
printf("%d\n",top->data);
top=top->link; // Now top points the previous node in the list
}
}
void push()
{
printf("\nENTER THE NEXT ELEMENT: ");
top=(struct node *)malloc(sizeof(struct node));
scanf("%d",&top->data);
top->link=temp;
temp=top;
}

void pop()
{
if(temp==NULL)
{
printf("\nSTACK IS EMPTY\n");
}
else
{
top=temp;
printf("\nDELETED ELEMENT IS %d\n",temp->data);
temp=temp->link;
free(top);
}
}
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n\n 1.CREATE \n 2.PUSH \n 3.POP \n 4.EXIT \n");
printf("\n ENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
display();
break;
case 2:
push();
display();
break;
case 3:
pop();
display();
break;
case 4:
exit(0);
}
}
}

SAMPLE INPUT AND OUTPUT:


STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE : 1
ENTER THE FIRST ELEMENT : 10
10
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 2
ENTER THE NEXT ELEMENT: 30
10
30
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 3
DELETED ELEMENT IS 30
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 3
DELETED ELEMENT IS 10
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 3
STACK IS EMPTY.

CPP Program To Implement Stack Using Single Linked List:


#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
class stack
{
int element;
stack* next;
public:
stack* push(stack*,int);
stack* pop(stack*);
void stack_display(stack*);
}*head,object;
stack* stack::push(stack* head,int key)
{
stack* temp,*temp1;
temp1=head;
temp=new stack;
temp->element=key;
temp->next=NULL;
if(head==NULL)
head=temp;
else
{
while(head->next!=NULL)
head=head->next;
head->next=temp;
head=temp1;
}
return head;
}
stack* stack::pop(stack* head)
{
stack* temp;
if(head!=NULL)
{
temp=head;
if(head->next==NULL)
{
cout<<"\nthe pooped element from the stack is: "<<head->element<<endl;
return NULL;
}
while(head->next->next!=NULL)
head=head->next;
cout<<"the popped element from the stack is "<<head->next->element;
cout<<endl;
head->next=head->next->next;
head=temp;
return head;
}
else
{
cout<<"\n\n STACK IS EMPTY ";
return head;
}
}
void stack::stack_display(stack* head)
{
if(head!=NULL)
{
while(head->next!=NULL)
{
cout<<endl<<head->element;
head=head->next;
}
cout<<endl<<head->element<<" --->TOP";
cout<<endl;
}
/*else
cout<<"\n\nTHE STACK IS EMPTY\n";*/
}
void choice()
{
int key,ch;
head=NULL;
clrscr();
while(1)
{
textcolor(15);
clrscr();
cout<<"\n\nMAIN MENU\n\n";
cout<<"\n1.PUSH\n2.POP\n3.EXIT\n\n";
cout<<"ENTER YOUR CHOICE : ";
cin>>ch;

switch(ch)
{
case 1:
cout<<"\n\nENTER THE ELEMENT TO PUSH STACK : ";
cin>>key;
head=object.push(head,key);
object.stack_display(head);
break;
case 2:
head=object.pop(head);
object.stack_display(head);
break;
case 3:
exit(1);
default:
cout<<"\n\nInvalid choice...\n";
break;
}
}
}
void main()
{
choice();
}

SAMPLE INPUT AND OUTPUT:


STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE : 1
ENTER THE FIRST ELEMENT : 10
10
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 2
ENTER THE NEXT ELEMENT: 30
10
30
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 3
DELETED ELEMENT IS 30
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 3
DELETED ELEMENT IS 10
STACK
1. CREATE
2. PUSH
3. POP
4. EXIT
ENTER YOUR CHOICE: 3
STACK IS EMPTY.
Implemention of Stack Using Array
Stack Definition:
In computer science, a stack is a last in, first out(LIFO) abstract data type and data structure. A stack
can have any abstract data type as an element, but is characterized by only two fundamental
operations, the push and the pop.
(or)
A collection of items in which only the most recently added item may be removed. The latest added item
is at the top. Basic operations are push and pop. Often top and is Empty are available, too. Also known
as "last-in, first-out" or LIFO.

Push:
The push operation adds to the top of the list, hiding any items already on the stack, or initializing the
stack if it is empty.

Pop:
The pop operation removes an item from the top of the list, and returns this value to the caller. A pop
either reveals previously concealed items, or results in an empty list.

Stack Applications:
1. Expression evaluation.
2. Backtracking (game playing, finding paths, exhaustive searching).
3. Memory management, run-time environment for nested language features.

Alogarithm steps:
Step 1: Define a stack size.
Step 2: Read the stack operation.
Step 3: Read the stack element.
Step 4: Check the stack operation is Push or Pop.
Step 5: If operation is push then check the stack status.
i. If stack status is over flow we can’t push the element in to stack.
ii. Otherwise we can add the data into stack .
iii. Move top to next position.

C Program To Implement Stack Using Array


CPP Program To Implement Stack Using Array

C Program To Implement Stack Using Array:


//Program for Stack implementation through Array
#include <stdio.h>
//#include <ctype.h>
#define MAXSIZE 5
int stack[MAXSIZE];
int top=0; //index pointing to the top of stack
void main()
{
void push();
void pop();
void display();
int will=1,i;
clrscr();
while(1)
{
printf("\n\n\nMAIN MENU:\n\n1.PUSH\n2.POP\n3.EXIT\n\nENTER
YOUR CHOICE: ");
scanf("%d",&will);
switch(will)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
case 3:
exit(0);
break;
default:
printf("Invalid Choice . ");
}

} //end of outer while


} //end of main

void push()
{
int num;
if(top>=MAXSIZE)
{
printf("\nSTACK FULL");
return;
}
else
{ if(top<0)
top=0;
printf("\n\nENTER THE STACK ELEMENT : ");
scanf("%d",&num);
stack[top++]=num;
}
}

void pop()
{
if(top>=0)
top--;

void display()
{
int i;
if(top<=0)
printf("\n\nSTACK EMPTY");
else
for(i=top-1;i>=0;i--)
{
printf("\n\n%d ",stack[i]);
if(i==(top-1))
printf("---->TOP");
}
}
SAMPLE INPUT OUTPUT:
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 10
10 ---->TOP
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 20
20 ---->TOP
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 30
STACK FULL
30 ---->TOP
20
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 2
20 ---->TOP
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 2
10 ---->TOP
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
STACK EMPTY
CPP Program To Implement Stack Using Array:
//Stack implementation as a class.
# include<iostream.h>
# include<process.h>
# include<conio.h>
# define SIZE 5
class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
void display();
void pop();
int isempty();
int isfull();
};
stack::stack()
{
tos=0; //Initialize Top of Stack
}

int stack::isempty()
{
return (tos==0?1:0);
}
int stack::isfull()
{
return (tos==SIZE?1:0);
}

void stack::push(int i)
{
if(!isfull())
{
a[tos]=i;
tos++;
}
else
{
cerr<<endl<<endl<<"Stack overflow error !Possible Data Loss !";
}
}
void stack::pop()
{
if(!isempty())
{
--tos;
cout<<endl<<endl<<"ELEMENT IS POPED";
}
else
{
cerr<<endl<<endl<<"Stack is empty! What to pop...!";
}
}
void stack ::display()
{
for(int i=tos-1;i>=0;i--)
cout<<endl<<a[i]<<endl;

}
void main()
{
stack s;
int ch=1,num;
clrscr();
while(ch!=0)
{
cout<<endl<<endl<<"MAIN
MENU"<<endl<<endl<<"1.Push"<<endl<<"2.Pop"<<endl<<"3.IsEmpty"<<endl<<"
4.IsFull"<<endl<<"0.Exit"<<endl<<endl;
cout<<"ENTER YOUR CHIOCE : ";
cin>>ch;
switch(ch)
{
case 0:
exit(1); //Normal Termination of Program
case 1:
cout<<endl<<endl<<"ENTER THE STACK ELEMENT : ";
cin>>num;
s.push(num);
s.display();
break;
case 2:
s.pop();
s.display();
break;
case 3:
(s.isempty())?(cout<<endl<<endl<<"Stack is
empty."):(cout<<endl<<endl<<"Stack is not empty.");
break;
case 4:
(s.isfull())?(cout<<endl<<endl<<"Stack is
full."):(cout<<endl<<endl<<"Stack is not full.");
break;
default:
cout<<endl<<endl<<"Illegal Option.Please try again";
}
}//end of while
getch();
}
SAMPLE INPUT OUTPUT:
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 10
10 ---->TOP
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 20
20 ---->TOP
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE STACK ELEMENT : 30
STACK FULL
30 ---->TOP
20
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 2
20 ---->TOP
10
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 2
10 ---->TOP
MAIN MENU :
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE : 1
STACK EMPTY
Implemention of Queue using Array
Queue:
A Queue is a linear data structure which follows First In First Out (FIFO) principle,
in which insertion is performed at rear end deletion is performed at front end.
(or)
A queue is a "waiting line" type of data structure. Much like with a stack, we can
insert items into a queue and remove items from a queue. However, a queue has "first
come, first served" behavior in that the first item inserted into the queue is the first
one removed.

Operations on Queue:
1.Enqueue
2.Dequeue
Exception condition:

Overflow: Attempt to insert an element, when the queue is full.

Underflow: Attempt to delete an element from the queue, when the queue is empty.

Uses of Queues:

Queues are commonly used in operating systems and other software where some sort of waiting line
has to be maintained for obtaining access to a resource. For example, an operating system may keep a
queue of processes that are waiting to run on the CPU. It might also keep a queue of print jobs that are
waiting to be printed on a printer. Queues are also used in simulations of stores and their waiting lines
at the check-out counters.

Alogarithm Steps:

Step 1: Initialize the queue variables front =0 and rear = -1


Step 2: Read the queue operation type.
Step 3: Check the queue operations status.
i). If it is Insertion then do the following steps
1. Check rear < queue_size is true increment the rear by one and read the queue element and
also display queue. other wise display the queue is full.
2. Go to step2.
ii). If it is deletion then do the following steps
1. Check rear< front is true then display the queue is empty.
2. Move the elements to one step forward (i.e. move to previous index ).
3. Decreases the rear value by one (rear=rear-1).
4. Display queue
5. Go to step2.
C Program To Implement Queue Using Array
CPP Program To Implement Queue Using Array

C Program To Implement Queue Using Array:


//queue using array
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int i,rear,front,item,s[SIZE];
void insert(int item,int s[]);
void del(int s[]);
void display(int s[]);
void main()
{
int ch;
clrscr();
front=0;
rear=-1;
do
{
printf("\n\n 1.INSERTION \n 2.DELETION \n 3.EXIT \n");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\t INSERTION \n");
if(rear>=SIZE-1)
{
printf("\t\nQUEUE IS FULL\n");
}
else
{
printf("\nENTER AN ELEMENT : ");
scanf("%d",&item);
insert(item,s);
}
display(s);
break;
case 2:
printf("\n\t DELETION \n");
if(front>rear)
{
printf("\t\nQUEUE IS EMPTY\n");
}
else
{
del(s);
}
display(s);
break;
}
}while(ch!=3);
getch();
}
void insert(int item,int s[])
{
if(rear<SIZE)
{
rear=rear+1;
s[rear]=item;
}
}
void del(int s[])
{
int i;
item=s[front];
for(i=0;i<=rear;i++)
s[i]=s[i+1];
rear--;
printf("\n DELETED ELEMENT IS %d\n\n",item);
}

void display(int s[])


{
printf("\n");
for(i=front;i<=rear;i++)
{
printf(" \t %d",s[i]);
}
}
SAMPLE INPUT OUTPUT:
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1

INSERTION
ENTER AN ELEMENT : 10
10
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 20
10 20
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 30
10 20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
QUEUE IS FULL
10 20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 10

20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 20

30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 30

1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
QUEUE IS EMPTY

CPP Program To Implement Queue Using Array:


# include<iostream.h>
# include<conio.h>
# include<process.h>
# define SIZE 5

class queue
{
int a[SIZE];
int front;
int rear;
public:
queue();
~queue();
void insert(int i);
void remove();
void display();
int isempty();
int isfull();
};

queue::queue()
{
front=0;
rear=0;
}
queue::~queue()
{
delete a;
}
void queue::insert(int i)
{
a[rear++] = i;
}
void queue::remove()
{
cout<<"\n\nDELETED ELEMENT IS : "<<a[front];
for(int i=0;i<rear;i++)
a[i]=a[i+1];
rear--;
}
void queue::display()
{
cout<<"\n";
for(int i=front;i<rear;i++)
cout<<"\t"<<a[i];
}
int queue::isempty()
{
if(front == rear)
return 1;
else
return 0;
}
int queue::isfull()
{
if(rear >= SIZE)
return 1;
else
return 0;
}

void main()
{
queue q;
int ch;
clrscr();
while(1)
{
cout<<"\n\nMAIN MENU";
cout<<"\n1.INSERTION";
cout<<"\n2.DELETION";
cout<<"\n3.EXIT";
cout<<"\n\nENTER YOUR CHOICE : ";
cin>>ch;
switch(ch)
{
case 1:
int num;
if(q.isfull())
{
cout<<"\nQUEUE IS FULL\n";
}
else
{
cout<<"\n\nENTER THE QUEUE ELEMENT : ";
cin>>num;
q.insert(num);
}

q.display();
break;
case 2:
if(q.isempty())
{
cout<<"\nQUEUE IS EMPTY\n ";
}
else
{
q.remove();
}
q.display();
break;
case 3:
exit(0);
default:
cout<<"Invalid choice...";
}
}
getch();
}

SAMPLE INPUT OUTPUT:


1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1

INSERTION
ENTER AN ELEMENT : 10
10
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 20
10 20
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
ENTER AN ELEMENT : 30
10 20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
INSERTION
QUEUE IS FULL
10 20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 10

20 30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 20

30
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
DELETED ELEMENT IS 30

1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETION
QUEUE IS EMPTY
Implementation of Queue Using Linked List
Queue:
A Queue is a linear data structure which follows First In First Out (FIFO) principle, in which insertion is
performed at rear end deletion is performed at front end.

(or)
A queue is a "waiting line" type of data structure. Much like with a stack, we can insert items into a
queue and remove items from a queue. However, a queue has "first come, first served" behavior in that
the first item inserted into the queue is the first one removed.

Operations on Queue:
1.Enqueue
2.Dequeue
Exception condition:

Overflow: Attempt to insert an element, when the queue is full

Underflow: Attempt to delete an element from the queue, when the queue is empty.

Uses of Queues:

Queues are commonly used in operating systems and other software where some sort of waiting line
has to be maintained for obtaining access to a resource. For example, an operating system may keep a
queue of processes that are waiting to run on the CPU. It might also keep a queue of print jobs that are
waiting to be printed on a printer. Queues are also used in simulations of stores and their waiting lines
at the check-out counters.

Alogarithm Steps:

Step 1: Create nodes first, last, cur

Step 2: Read the queue operation.

Step 3: Create a list.

1. Create a new empty node cur.


2. Allocate memory for the node cur.
3. Read the queue’s first element in cur node’s data part.
4. Assign cur node’s link part as Null.
5. Assign first=last=cur.
Step 4: If the queue operation is Insertion then do the following steps

1. Create a new empty node cur.


2. Allocate memory for the node cur.
3. Read the queue’s element in cur node’s data part.
4. Assign cur node’s link part as null.
5. Assign last = cur.

Step 5: If the queue operation is Deletion then do the following steps.

1. If first equal to NULL then display queue is empty.


2. Assign cur as first. (i.e. cur=first).
3. Assign first as first of link (i.e. first=first->link).
4. Assign cur of link as NULL. (i.e. cur->link=NULL).
5. Reallocate the node cur from memory.

Step 6: If the operation is Display then do the following steps

1. Assign cur as first.


2. Repeat until cur becomes Null.
1. Display cur node’s data.
2. Assign cur as cur of link.
Step 7: go to step 2.

C Program To Implement Queue Using linked list:


CPP Program To Implement Queue Using linked list

C Program To Implement Queue Using linked list:

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *cur,*first,*last;

void create();
void insert();
void delte();
void display();

void create()
{
printf("\nENTER THE FIRST ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;
}
void insert()
{
printf("\nENTER THE NEXT ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
last->link=cur;
last=cur;
}
void delte()
{
if(first==NULL)
{
printf("\t\nQUEUE IS EMPTY\n");
}
else
{
cur=first;
first=first->link;
cur->link=NULL;
printf("\n DELETED ELEMENT IS %d\n",cur->data);
free(cur);
}
}
void display()
{
cur=first;
printf("\n");
while(cur!=NULL)
{
printf("\t%d",cur->data);
cur=cur->link;
}
}

void main()
{
int ch;
clrscr();
while(1)
{
printf("\n\n 1.CREATE \n 2.INSERT \n 3.DELETE \n 4.EXIT \n");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
display();
break;
case 2:
insert();
display();
break;
case 3:
delte();
display();
break;
case 4:
exit(0);
}
}
}

SAMPLE INPUT OUTPUT :


1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 1

ENTER AN ELEMENT : 10
10
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 2

ENTER AN ELEMENT : 20
10 20
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 2

ENTER AN ELEMENT : 30
10 20 30

1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3

DELETED ELEMENT IS 10
20 30
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3

DELETED ELEMENT IS 20
30
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3

DELETED ELEMENT IS 30

1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3
QUEUE IS EMPTY
CPP Program To Implement Queue Using linked list:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *cur,*first,*last;

void create();
void insert();
void delte();
void display();

void create()
{
printf("\nENTER THE FIRST ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;
}
void insert()
{
printf("\nENTER THE NEXT ELEMENT: ");
cur=(struct node *)malloc(sizeof(struct node));
scanf("%d",&cur->data);
cur->link=NULL;
last->link=cur;
last=cur;
}
void delte()
{
if(first==NULL)
{
printf("\t\nQUEUE IS EMPTY\n");
}
else
{
cur=first;
first=first->link;
cur->link=NULL;
printf("\n DELETED ELEMENT IS %d\n",cur->data);
free(cur);
}
}
void display()
{
cur=first;
printf("\n");
while(cur!=NULL)
{
printf("\t%d",cur->data);
cur=cur->link;
}
}

void main()
{
int ch;
clrscr();
while(1)
{
printf("\n\n 1.CREATE \n 2.INSERT \n 3.DELETE \n 4.EXIT \n");
printf("\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
display();
break;
case 2:
insert();
display();
break;
case 3:
delte();
display();
break;
case 4:
exit(0);
}
}
}

SAMPLE INPUT OUTPUT:


1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 1

ENTER AN ELEMENT : 10
10
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 2

ENTER AN ELEMENT : 20
10 20
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 2

ENTER AN ELEMENT : 30
10 20 30

1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3

DELETED ELEMENT IS 10
20 30
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3

DELETED ELEMENT IS 20
30
1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3

DELETED ELEMENT IS 30

1.CREATE
2.INSERTION
3.DELETION
4.EXIT
ENTER YOUR CHOICE : 3
QUEUE IS EMPTY
Implementation of Circular Queue Using Array:
Definition:
An implementation of a bounded queue using an array.
(or)
In circular queue, the insertion of a new element is performed at the very first location of the queue
if the last location of the queue is full, in which the first element comes just after the last element.
Advantages :
It overcomes the problem of unutilized space in leaner queues, when it is implemented as arrays.
Insertion :
Rear = (rear+1)%Maxsize
Alogarithm Steps:
Step 1: create and set the variables front,rear,MAXSIZE,cq[]
step 2: Read the circular queue opeartion type.
step 3: If operation type is Insertion below steps are executed.
1.Assign rear=rear%MAXSIZE.
2.if front equal to (rear+1)%MAXSIZE then display queue is overflow.
3.if front equal to -1 then assign front=rear=0.
4.Otherwise assign rear=(rear+1)%MAXSIZE and read queue data .
5.Assign cq[rear] as data.(i.e. cq[rear]=data).
step 4: If operation type is Deletion below steps are executed.
1.Check front=-1 then display queue is underflow.
2.Set temp as cq[front] (i.e. temp=ca[front]).
3.Check front equal to rear if it is true then assign front=rear=-1(Move the front to begining)
4.Assign front=(front+1)%MAXSIZE.
C Program To Implement Circular Queue Using Array
CPP Program To Implement Circular Queue Using Array

C Program To Implement Circular Queue Using Array:

//Program for Circular Queue implementation through Array


#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define MAXSIZE 5
int cq[MAXSIZE];
int front,rear;
void main()
{
void add(int,int);
void del(int);
int will=1,i,num;
front = -1;
rear = -1;
clrscr();
printf("\nProgram for Circular Queue demonstration through array");
while(1)
{
printf("\n\nMAIN MENU\n1.INSERTION\n2.DELETION\n3.EXIT");
printf("\n\nENTER YOUR CHOICE : ");
scanf("%d",&will);
switch(will)
{
case 1:
printf("\n\nENTER THE QUEUE ELEMENT : ");
scanf("%d",&num);
add(num,MAXSIZE);
break;
case 2:
del(MAXSIZE);
break;
case 3:
exit(0);
default: printf("\n\nInvalid Choice . ");
}

} //end of outer while


} //end of main
void add(int item,int MAX)
{
//rear++;
//rear= (rear%MAX);
if(front ==(rear+1)%MAX)
{
printf("\n\nCIRCULAR QUEUE IS OVERFLOW");
}
else
{
if(front==-1)
front=rear=0;
else
rear=(rear+1)%MAX;
cq[rear]=item;
printf("\n\nRear = %d Front = %d ",rear,front);
}
}
void del(int MAX)
{
int a;
if(front == -1)
{
printf("\n\nCIRCULAR QUEUE IS UNDERFLOW");
}
else
{
a=cq[front];
if(front==rear)
front=rear=-1;
else
front = (front+1)%MAX;
printf("\n\nDELETED ELEMENT FROM QUEUE IS : %d ",a);
printf("\n\nRear = %d Front = %d ",rear,front);

}
}
SAMPLE INPUT OUTPUT.
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 10
Rear=0 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 20
Rear=1 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 30
Rear=2 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 40
Rear=3 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 50
Rear=4 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 60
CIRCULAR QUEUE IS OVERFLOW.
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 10
Rear =4 Front=1
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 20
Rear =4 Front=2
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 30
Rear =4 Front=3
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 40
Rear =4 Front=4
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 50
Rear =-1 Front=-1
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
CIRCULAR QUEUE IS UNDERFLOW.
CPP Program To Implement Circular Queue Using Array:
#include<iostream.h>
#include<conio.h>
#include<process.h>
#define MAX 4 /*for array size*/
class cirq
{
private:int arr[MAX];
int front,rear,count; /*count to know the no of ele. Present in array.*/
public:
cirq();
void push(int n);
void pop();
void display();
~cirq();
};
cirq::cirq()
{
front = rear =-1;
count=0;
}
void cirq:: push(int n)
{
if(count<MAX)
{
if(front ==-1)
{
front=rear=0;
}
else if(rear==MAX-1) /* if rear is at maximum position then bring it in starting*/
rear=0;
else
rear++;
arr[rear]=n;
count++;
}
else
{
cout<<endl<<"\nqueue is full don't enter now";
}
}
void cirq::pop()
{
if(count>0)
{
cout<<endl<<"\ndeleted item is"<<arr[front];
if(front==MAX-1) /* if front is at maximum position then bring it in starting*/
front=0;
else
front++;
count--;
}
else
cout<<endl<<"\ncircular queue is empty";
}
void cirq::display()
{
int local = count;
int front1=front;
if(local<0) /*if there is no element in quque*/
{
cout<<endl<<"\ncircular queue is empty";
}
else
{
cout<<endl<<"\ncircular queue elements are: ";
while(local)
{
cout<<endl<<arr[front1];
if(front1==MAX-1) /* if front is at maximum position then bring it in starting*/
front1=0;
else
front1++;
local--;
}
}
}
cirq::~cirq()
{
}
int main()
{
cirq q;
int ch,num;
clrscr();
while(1)
{
cout<<"\n\nMAIN MENU";
cout<<"\n1.INSERTION";
cout<<"\n2.DELETION";
cout<<"\n3.EXIT";
cout<<"\n\nENTER YOUR CHOICE : ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n\nENTER THE ELEMENT : ";
cin>>num;
q.push(num);
q.display();
break;
case 2:
q.pop();
q.display();
break;
case 3:
exit(0);
default:
cout<<"\n\nINVALID CHOICE....";
}
}
getch();
return 0;
}

SAMPLE INPUT OUTPUT:


MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 10
Rear=0 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 20
Rear=1 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 30
Rear=2 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 40
Rear=3 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 50
Rear=4 Front=0
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 1
ENTER THE QUEUE ELEMENT : 60
CIRCULAR QUEUE IS OVERFLOW.
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 10
Rear =4 Front=1
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 20
Rear =4 Front=2
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 30
Rear =4 Front=3
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 40
Rear =4 Front=4
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
DELETED ELEMENT FROM QUEUE IS : 50
Rear =-1 Front=-1
MAIN MENU
1. INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE : 2
CIRCULAR QUEUE IS UNDERFLOW.
Implementation Of Single Linked List:
Definition:
In computer science, a linked list is a data structure that consists of a sequence of data records such
that in each record there is a field that contains a reference (i.e., a link) to the next record in the
sequence.
(or)
Linked list consists of series of nodes.Each node contains the element and a pointer to its successor
node. The pointer of the last node points to NULL. Each record of a linked list is often called an
element or node. The remaining fields may be called the data, information, value, or payload fields.
The field of each node that contains address of the next node is usually called the next link or next
pointer.

Types of Linked list:


1. Singly linked list.
2. Doubly linked list.
3. Circular linked list.
Advantages:
1. Length of the list need not be known in advance
2. Optimum use of memory
3. Insertion of element into the list is easier
4. Deletion of element from the list is easier
5. Concatenation of two linked lists is easier
6. Memory is not wasted if you remove an element from the list as it is freed

Singly linked list:

The simplest kind of linked list is a singly-linked list, which has one link per node. This link
points to the next node in the list, or to a null value or empty list if it is the final node.

A singly linked list's node is divided into two parts. The first part holds or points to
information about the node, and second part holds the address of next node. A singly linked list
travels one way.
Operations on singly linked list:
1. Insert the element in the list.
2. Delete the element in the list
3. Forward traverse.
Advantages of singly linked list:
1. Dynamic data structure.
2. We can perform deletion and insertion anywhere in the list.
3. We can merge two list easily.
Disadvantages of singly linked list:
1. Backward traversing is not possible in singly linked list.
2. Insertion is easy but deletion take some additional time, because disadvantage of backward
traversing.
Algorithm steps:
Step1: Create nodes first, last, next, prev and cur then set the value as NULL.

Step 2: Read the list operation type.

step 3: If operation type is create then process the following steps.

1. Allocate memory for node cur.

2. Read data in cur's data area.

3. Assign cur link as NULL.

4. Assign first=last=cur.

Step 4: If operation type is Insert then process the following steps.

1. Allocate memory for node cur.

2. Read data in cur's data area.

3. Read the position the Data to be insert.

4. Availability of the position is true then assing cur's link as first and first=cur.

5. If availability of position is false then do following steps.

1. Assign next as cur and count as zero.

2. Repeat the following steps until count less than postion.

1 .Assign prev as next

2. Next as prev of link.

3. Add count by one.

4. If prev as NULL then display the message INVALID POSITION.

5. If prev not qual to NULL then do the following steps.

1. Assign cur's link as prev's link.

2. Assign prev's link as cur.


Step5: If operation type is delete then do the following steps.

1. Read the position .


2. Check list is Empty .If it is true display the message List empty.

3. If position is first.

1. Assign cur as first.

2. Assign First as first of link.

3. Reallocate the cur from memory.

4. If position is last.

1. Move the current node to prev.

2. cur's link as Null.

3. Reallocate the Last from memory.

4. Assign last as cur.

5. If position is enter Mediate.

1. Move the cur to required postion.

2. Move the Previous to cur's previous position

3. Move the Next to cur's Next position.

4. Now Assign previous of link as next.

5. Reallocate the cur from memory.

step 6: If operation is traverse.


1. Assign current as first.

2. Repeat the following steps untill cur becomes NULL.


C Program To Implement Single Linked List
CPP Program To Implement Single Linked List

C Program To Implement Single Linked List:

#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void create();
void insert();
void delet();
void display();
struct node
{
int data;
struct node *link;
};
struct node *first=NULL,*last=NULL,*next,*prev,*cur;
void create()
{
cur=(struct node*)malloc(sizeof(struct node));
printf("\nENTER THE DATA: ");
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
last=cur;
}
void insert()
{
int pos,c=1;
cur=(struct node*)malloc(sizeof(struct node));
printf("\nENTER THE DATA: ");
scanf("%d",&cur->data);
printf("\nENTER THE POSITION: ");
scanf("%d",&pos);
if((pos==1) &&(first!=NULL))
{
cur->link = first;
first=cur;
}
else
{
next=first;
while(c<pos)
{
prev=next;
next=prev->link;
c++;
}
if(prev==NULL)
{
printf("\nINVALID POSITION\n");
}
else
{
cur->link=prev->link;
prev->link=cur;
}
}
}
void delet()
{
int pos,c=1;
printf("\nENTER THE POSITION : ");
scanf("%d",&pos);
if(first==NULL)
{
printf("\nLIST IS EMPTY\n");
}
else if(pos==1 && first->link==NULL)
{
printf("\n DELETED ELEMENT IS %d\n",first->data);
free(first);
first=NULL;
}
else if(pos==1 && first->link!=NULL)
{
cur=first;
first=first->link;
cur->link=NULL;
printf("\n DELETED ELEMENT IS %d\n",cur->data);
free(cur);
}
else
{
next=first;
while(c<pos)
{
cur=next;
next=next->link;
c++;
}
cur->link=next->link;
next->link=NULL;
if(next==NULL)
{
printf("\nINVALID POSITION\n");
}
else
{
printf("\n DELETED ELEMENT IS %d\n",next->data);
free(next);
}
}
}
void display()
{
cur=first;
while(cur!=NULL)
{
printf("\n %d",cur->data);
cur=cur->link;
}
}
void main()
{
int ch;
clrscr();
printf("\n\nSINGLY LINKED LIST");
do
{
printf("\n\n1.CREATE\n2.INSERT\n3.DELETE\n4.EXIT");
printf("\n\nENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
create();
display();
break;
case 2:
insert();
display();
break;
case 3:
delet();
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice...");
}
}while(1);
}
SAMPLE INPUT AND OUTPUT:
SINGLY LINKED LIST
1.CREATE
2.INSERT
3.DELETE
4.EXIT
ENTER YOUR CHOICE : 1
ENTER THE DATA: 10
10
1.CREATE
2.INSERT
3.DELETE
4.EXIT
ENTER YOUR CHOICE : 2
ENTER THE DATA: 30
ENTER THE POSITION: 1
30
10
1.CREATE
2.INSERT
3.DELETE
4.EXIT
ENTER YOUR CHOICE : 3
ENTER THE POSITION : 2
LIST IS EMPTY

CPP Program To Implement Single Linked List:

/* single linked list */


#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class list
{
struct node
{
int data;
node *link;
}*p;
public:
void inslast(int);
void insbeg(int);
void insnext(int,int);
void delelement(int);
void delbeg();
void dellast();
void disp();
int seek(int);
list(){p=NULL;}
~list();
};

void list::inslast(int x)
{
node *q,*t;
if(p==NULL)
{
p=new node;
p->data=x;
p->link=NULL;
}
else
{
q=p;
while(q->link!=NULL)
q=q->link;
t=new node;
t->data=x;
t->link=NULL;
q->link=t;
}
cout<<"\n\nInserted successfully at the end..";
disp();
}

void list:: insbeg(int x)


{
node *q;
q=p;
p=new node;
p->data=x;
p->link=q;
cout<<"\n\nInserted successfully at the begining..";
disp();
}

void list::delelement(int x)
{
node *q,*r;
q=p;
if(q->data==x)
{
p=q->link;
delete q;
return;
}
r=q;
while(q!=NULL)
{
if(q->data==x)
{
r->link=q->link;
delete q;
return;
}
r=q;
q=q->link;
}
cout<<"\n\nElement you entered "<<x<<" is not found..";
}

void list:: delbeg()


{
cout<<"\n\nThe list before deletion:";
disp();
node *q;
q=p;
if(q==NULL)
{
cout<<"\n\nNo data is present..";
return;
}
p=q->link;
delete q;
return;
}

void list:: dellast()


{
cout<<"\n\nThe list before deletion:";
disp();
node *q,*t;
q=p;
if(q==NULL)
{
cout<<"\n\nThere is no data in the list..";
return;
}
if(q->link==NULL)
{
p=q->link;
delete q;
return;
}

while(q->link->link!=NULL)
q=q->link;
q->link=NULL;
return;
}

list::~list()
{
node *q;
if(p==NULL) return;
while(p!=NULL)
{
q=p->link;
delete p;
p=q;
}
}

void list::disp()
{
node *q;
q=p;
if(q==NULL)
{
cout<<"\n\nNo data is in the list..";
return;
}
cout<<"\n\nThe items present in the list are \n";
while(q!=NULL)
{
cout<<q->data<<"\n";
q=q->link;
}
}

void list :: insnext(int value,int position)


{
node *temp,*temp1;
temp=p;
if(temp1==NULL)
{
temp1= new node;
temp1->data=value;
temp1->link=NULL;
p=temp1;
return;
}
for(int i=0;((i<position)&&(temp->link!=NULL)) ;i++)
{
if(i==(position-1))
{
temp1= new node;
temp1->data= value;
temp1->link=temp->link;
temp->link=temp1;
}
temp=temp->link;
}
cout<<"\n\nInserted successfully at "<<position;
disp();
}

int list::seek(int value)


{
node *temp;
temp=p;
int position=0;
while(temp!=NULL)
{
if(temp->data==value)
return position+1;
else
{
temp=temp->link;
position=position+1;
}
}
cout<<"\n\nElement "<<value<<" not found";
return 0;
}

void main()
{
list l;
int ch,v,p,ps;
do
{
clrscr();
cout<<"\n\nOperations on List..";
cout<<"\n\n1.Insertion\n2.Deletion\n3.Display\n4.Seek\n5.Exit";
cout<<"\n\nEnter ur Option :";
cin>>ch;

switch(ch)
{
case 1:
clrscr();
cout<<"INSERTION";
cout<<"\n\n1.Insertion at begining\n2.Insertion at the end";
cout<<"\n3.Insertion between two Nodes";
cout<<"\n\nEnter ur choice:";
cin>>ps;
cout<<"Enter the value to insert:";
cin>>v;
switch(ps)
{
case 1:
l.insbeg(v);
break;
case 2:
l.inslast(v);
break;
case 3:
cout<<"\nEnter the position to insert the value:";
cin>>p;
l.insnext(v,p);
break;

default:
cout<<"\nThe choice is invalid";
return;
}
break;

case 2:
clrscr();
cout<<"\n1.Delete the first element\n2.Delete the last element";
cout<<"\n3.Enter the element to delete from the list";
cout<<"\n\nEnter ur choice:";
cin>>ps;
switch(ps)
{
case 1:
l.delbeg();
cout<<"\nThe list after deletion:";
l.disp();
break;
case 2:
l.dellast();
cout<<"\nThe list after deletion:";
l.disp();
break;
case 3:
l.disp();
cout<<"\nEnter the element to delete : ";
cin>>v;
l.delelement(v);
cout<<"\nThe list after deletion:";
l.disp();
break;

default:
cout<<"\nThe option is invalid...";
break;
}
break;

case 3:
clrscr();
l.disp();
break;

case 4:
clrscr();
l.disp();
cout<<"\nEnter the element to search:";
cin>>v;
cout<<"\nThe position of the element "<< v<<" is "<<l.seek(v);
getch();
break;

case 5:
exit(1);

default:
cout<<"\nThe option is invalid...";
return;
}
getch();
}while(ch!=5);
getch();
return;
}

SAMPLE INPUT AND OUTPUT:


SINGLY LINKED LIST
1.CREATE
2.INSERT
3.DELETE
4.EXIT
ENTER YOUR CHOICE : 1
ENTER THE DATA: 10
10
1.CREATE
2.INSERT
3.DELETE
4.EXIT
ENTER YOUR CHOICE : 2
ENTER THE DATA: 30
ENTER THE POSITION: 1
30
10
1.CREATE
2.INSERT
3.DELETE
4.EXIT

ENTER YOUR CHOICE : 3


ENTER THE POSITION : 2
LIST IS EMPTY

Implementation Of Double Linked List:


Definition:

A variant of a linked list in which each item has a link to the previous item as well as the next. This
allows easily accessing list items backward as well as forward and deleting any item in constant
time.
Also known as two-way linked list, symmetrically linked list.
A doubly linked list is a linked list in which each node has three fields namely data field, forward
link (Flink) and backward link (Blink). Flink points to the successor node in the list whereas Blink
points to the predecessor node.
Advantages:
1. Deletion process is easier
2. Additional pointer for previous node is not nessary.
3. Backwarding and forwarding traverse are possible.
Disadvantages :
1. More Memory space is required since it has two pointers.
Alogrithm steps:

Step 1: Read the list operation.


Step 2: If operation is Create then process the following steps.
1. Create the new node and allocate memory for the new node.
2. Read the data in the new node.
3. Assign Flink and Blink as NULL.
4. Assign current as new.
Step 3: If operation is Insertion do the following steps.
i) Check insertion at beginning is true then

1. Create the new node and allocate memory for the new node
2. Read the data in the new node.
3. Move the current node to start position
4. Assign new->Blink =Null
5. Assign new->Flink=current
6. Now assign current->Blink=new
ii) Insertion at between nodes is true then

1. Create the new node and allocate memory for the new node
2. Read the data in the new node.
3. Move the current node required position
4. Assign new node‟s Blink=current.
5. Assign new node‟s Flink=current->Flink
6. Assign current node‟s Flink =new
iii) Insertion at between nodes is true then

1. Create the new node and allocate memory for the new node.
2. Read the data in the new node.
3. Move the current node to end position.
4. Assign current node‟s Flink =new.
5. Assign new‟s Blink as current.
6. Assign new‟s Flink as NULL.
7. Move end pointer to new node.
Step 4: If operation is deletion then do the following steps.
i). Check deletion at beginning is true then.
1. Move current pointer to start position.
2. Move the start pointer next node in the link.
3. Assign start‟s Blink as NULL.
4. Reallocate current node from memory.
ii) Check deletion between two nodes is true

1. Move the current pointer to required position.


2. Assign current‟s->Blink->Flink as current‟s Flink.
3. Assign currents‟s->Flink->Blink as current‟s Blink.
4. Reallocate current from memory.
iii) Check deletion at end is true

1. Move the current pointer to end position.


2. Assign current‟s->Blink->Flink as Null.
3. Reallocate current from memory.
4. Reallocate current from memory.
Step 5: If the operation is traversing.
i) Check deletion at end is true

1. Move the current pointer to end position.


2. Repeat the following steps until current becomes NULL.
3. Display the data.
4. Current=current->Flink.
ii) If Backward traversing then
1. Move the current to end position.
2. Repeat the following steps until current becomes NULL.
3. Display the data.
4. Current=current->Flink.
C Program To Implement Double linked list

CPP Program To Implement Double linked list

C Program To Implement Double Linked List:


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
#define NULL 0

struct linkedlist
{
int item;
struct linkedlist *right,*left;
};

typedef struct linkedlist node;

void main()
{
node *start,*end;
int choice;
int menu(void);
node *create(node **lastnode);
void display(node *first,node *last);
void insert(node **first,node **last);
void del(node **first,node **last);
clrscr();
printf("\n DOUBLY LINKED LIST");
printf("\n ******************");
do
{
printf("\n\nMain menu");
printf("\n\n1.Create \n2.Insert \n3.Delete \n4.Display \n5.Exit");
choice =menu();

switch(choice)
{

case 1:
printf("\n Enter the data(-999 to stop):");
start=create(&end);
continue;

case 2:
insert(&start,&end);
printf("\n");
continue;

case 3:
del(&start,&end);
printf("\n");
continue;

case 4:
display(start,end);
printf("\n");
continue;

case 5:
exit(0);
default:
printf("\n\nINVALID CHOICE...");
}
}while(1);
}

int menu()
{
int choice;
do
{
printf("\n Enter your choice:");
scanf("%d",&choice);
if(choice<1||choice>5)
printf("\n Wrong choice");
}while(choice<1||choice>5);
printf("\n");
return(choice);
}

node *create(node **lastnode)


{
node *temp,*firstnode;
int info;
*lastnode=NULL;
firstnode=NULL;
scanf("%d",&info);
while(info!=-999)
{
temp=(node *)malloc(sizeof(node));
temp->item=info;
temp->right=NULL;
if(firstnode==NULL)
{
temp->left=NULL;
firstnode=temp;
}
else
{
temp->left=(*lastnode);
(*lastnode)->right=temp;
}
(*lastnode)=temp;
scanf("%d",&info);
}
if(firstnode!=NULL)
(*lastnode)=temp;
return(firstnode);
}

void display(node *first,node *last)


{
printf("\n Forward traversal\n");
while(first!=NULL)
{
printf("%d\t",first->item);
first=first->right;
}
printf("\n Backward traversal\n");
while(last!=NULL)
{
printf("%d\t",last->item);
last=last->left;
}
return;
}

void insert(node **first,node **last)


{
node *newnode;
int newitem;
int position;
node *temp;
int i;
printf("\n New data item:");
scanf("%d",&newitem);
do
{
printf("\n Position of insertion:");
scanf("%d",&position);
}while(position<=0);
if(((*first)==NULL)||(position==1))
{
newnode=(node *)malloc(sizeof(node));
newnode->item=newitem;
newnode->right=*first;
newnode->left=NULL;
if((*first)!=NULL)
(*first)->left=newnode;
else
(*last)=newnode;
*first=newnode;
}
else
{
i=1;
temp=*first;
while((i<position-1)&&(temp->right!=NULL))
{
i++;
temp=temp->right;
}
newnode=(node *)malloc(sizeof(node));
newnode->item=newitem;
newnode->right=temp->right;
if(temp->right!=NULL)
temp->right->left=newnode;
newnode->left=temp;
temp->right=newnode;
}
if(newnode->right==NULL)
*last=newnode;
}

void del(node **first,node **last)


{
node *temp,*prev;
int target;
printf("\n Enter the data to be deleted:");
scanf("%d",&target);
if(*first==NULL)
printf("\n List is empty");
else if((*first)->item==target)
{
if((*first)->right==NULL)
*first=*last=NULL;
else
{
*first=(*first)->right;
(*first)->left=NULL;
}
}
else
{
temp=*first;
prev=NULL;
while((temp->right!=NULL)&&(temp->item!=target))
{
prev=temp;
temp=temp->right;
}
if(temp->item!=target)
printf("\n Element not found");
else
{
if(temp==*last)
*last=prev;
else
temp->right->left=temp->left;
prev->right=temp->right;
}
}
}

Sample Input Output:


Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:1
Enter the data(-999 to stop):
5
10
15
-999
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:2
New data item:20
Position of insertion:
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
5 20 10 15 20

Backward traversal
20 15 10 20 5
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:3
Enter the data to be deleted:5
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
20 10 15 20
Backward traversal
20 15 10 20

CPP Program To Implement Double Linked List:

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
struct list
{
int data;
struct list*next;
struct list *prev;
};
typedef struct list node;
node *find(node *,int);
node *pre=NULL;
node *fin=NULL;
node *start;
int main()
{
int menu(void);
void create(node *);
void display(node *);
void insert(node *,int,int);
void reverse(node *);
void del(node *,int);
int choice,ch;
int data,tar;
node *newrec;
start=NULL;
clrscr();
do
{
choice=menu();
switch(choice)
{
case 1:
cout<<"\nCreating the list";
cout<<"Enter the terms(type 0 to end)\n";
start=new node;
create(start);
break;
case 2:
if (start==NULL)
cout<<"\nList does not exist";
else
{
cout<<"\nDisplaying the list\n";
display(start);
}
getch();
break;
case 3:
if (start==NULL)
{
cout<<"\nList does not exist";
getch();
}
else
{
cout<<"\nDisplaying the list:";
reverse(fin);
}
break;
case 4:
if(start==NULL)
{
cout<<"\nList does not exist";
getch();
}
else
{
cout<<"\nEnter the term to insert:";
cin>>data;
cout<<"\nEnter target term:";
cin>>tar;
insert(start,data,tar);
}
break;
case 5:
if(start==NULL)
{
cout<<"\nlist does not exist:";
getch();
}
else {
cout<<"\nEnter the term to delete:";
cin>>data;
del(start,data);
}
break;
case 6:
exit(0);
default:
cout<<"\nNot a valid choice";
}
}while(1);
return(0);
}
int menu(void)
{
int ch;
cout<<"\n1->Creation of the list";
cout<<"\n2->Displaying of the list";
cout<<"\n3->Reverse Displaying the list";
cout<<"\n4->Insertion of the list";
cout<<"\n5->Deletion of the list";
cout<<"\n6->Exit";
cout<<"\n\nEnter your choice:";
cin>>ch;
return(ch);
}
void create(node *record)
{
cin>>record->data;
if(record->data==0)
{
record->next=NULL;
record->prev=pre;
fin=record->prev;
pre=NULL;
}
else
{
record->prev=pre;
record->next=new node;
pre=record;
create(record->next);
}
return;
}
void display(node *record)
{
if(record->next!=NULL)
{
cout<<record->data<<" ";
display(record->next);
}
return;
}
void reverse(node *record)
{
if(record->prev!=NULL)
{
cout<<record->data<<" ";
reverse(record->prev);
}
return;
}
void insert(node *record,int data,int target)
{
node *tag,*newrec,*temp;
newrec=new node;
if(record->data==target)
{
newrec->next=record;
newrec->prev=NULL;
record->prev=newrec;
start=newrec;
}
else
{
tag=find(record,target);
temp=tag->prev;
tag->prev=newrec;
newrec->next=tag;
temp->next=newrec;
}
if(tag==NULL)
{
cout<<"Target item not present in the list\n";
getch();
return;
}
newrec->data=data;
return;
}
void del(node *record,int target)
{
node *tag,*temp;
if(record->data==target)
{
temp=record;
start=start->next;
start->prev=NULL;
delete temp;
}
else
{
tag=find(record,target);
if(tag->next->next==NULL)
{
fin=fin->prev;
fin->next=tag->next;
}
if(tag==NULL)
{
cout<<"Target item not present in the list\n";
getch();
return;
}
return;
}
}
node *find(node *record,int target)
{
if(record->next->data==target)
{
return(record);
}
else if(record->next==NULL)
return(NULL);
else
find(record->next,target);
}

Sample Input Output:


Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:1
Enter the data(-999 to stop):
5
10
15
-999
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:2
New data item:20
Position of insertion:
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
5 20 10 15 20

Backward traversal
20 15 10 20 5
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:3
Enter the data to be deleted:5
Main menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter your choice:4
Forward traversal
20 10 15 20

Backward traversal
20 15 10 20
Implementation Of Circular Linked List:
Circular Linked List:
In circular linked list the pointer of the last node points to the first node.

It can be implemented as singly linked list and doubly linked list.


Advantages of Circular Linked List:

1. It allows traversing the list starting at any point.

2. It allows quick access to the first and last records.

3. Circularly doubly linked list allows traversing the list in either direction.
Algorithm Steps:

Step 1: Create the pointers prev, cur ,last.

Step 2: Read the operation type of the list.

Step 3: If the operation type is Insertion then

i) If insertion at beginning is true


1. Create the new node and allocate memory for that node.
2. Read the data in new nodes data part.
3. Assign cur->link = last->link (now cur->points first node)
4. Assign first=cur (move the first to cur)
5. Assign last->link =first (now last -> link points new first node)
ii) If insertion at between any two nodes is true
1. Move the prev pointer to required position
2. Create the new node and allocate memory for that node.
3. Read the data in new nodes data part.
4. Assign cur->link = prev-link (give the link to next node)
5. Assign prev->link =cur.
iii) If insertion at end is true
1. Move the prev is to last position ( ).
2. Create the new node and allocate memory for that node.
3. Read the data in new nodes data part.
4. Assign cur->link =prev->link
5. Assing prev=cur.
Step 4: If the operation type is deletion then

i) If deletion at beginning is true then


1. Assign first=last->link->link (Move the first to second position)
2. Assign cur=last->link
3. Assign last->link=first
4. Reallocate the cur from memory.
ii) If deletion between any two nodes is true
1. Move the cur to required position.
2. Move the prev to cur predecessor‟s position.
3. Assign prev->link=cur->link
4. Reallocate cur from memory.

iii). If deletion at ends is true

1. Move the cur to last position.


2. Move the prev to cur‟s predecessor position
3. Assign prev->link=cur->link
4. Reallocate cur from memory
Step 5: If operation type is traverses
1. Assign cur=first
2. Repeat the process untill cur becomes last Cur=cur->link
C Program To Implement Circular linked list

CPP Program To Implement Circular linked list

C Program To Implement Circular Linked List:

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define NULL 0
struct listelement
{
int item;
struct listelement *next;
};
typedef struct listelement node;

int menu()
{
int choice;
do
{
printf("\n\n MAIN MENU");
printf("\n ---------");
printf("\n 1.CREATE \n 2.INSERT \n 3.DELETE \n 4.Exit");
printf("\n Enter your choice:");
scanf("%d",&choice);
if(choice<1||choice>4)
printf("\n Wrong choice");
}while(choice<1||choice>4);
return(choice);
}

node *create(node **lastnode)


{
node *temp,*firstnode;
int info;
*lastnode=NULL;
firstnode=NULL;
printf("\n Enter the data:");
scanf("%d",&info);
while(info!=-999)
{
temp=(node *)malloc(sizeof(node));
temp->item=info;
temp->next=NULL;
if(firstnode==NULL)
firstnode=temp;
else
(*lastnode)->next=temp;
(*lastnode)=temp;
scanf("%d",&info);
}
if(firstnode!=NULL)
temp->next=firstnode;
return(firstnode);
}

void display(node *first,node *last)


{
do
{
printf("\t %d",first->item);
first=first->next;
}while(last->next!=first);
return;
}

void insert(node **first,node **last)


{
node *newnode;
node *temp;
int newitem,pos,i;
printf("\n Enter the new item:");
scanf("%d",&newitem);
printf("\n Position of insertion:");
scanf("%d",&pos);
if(((*first)==NULL)||(pos==1))
{
newnode=(node *)malloc(sizeof(node));
newnode->item=newitem;
newnode->next=*first;
*first=newnode;
if((*last)!=NULL)
(*last)->next=*first;
}
else
{
i=1;
temp=*first;
while((i<(pos-1)) && ((temp->next)!=(*first)))
{
i++;
temp=temp->next;
}
newnode=(node *)malloc(sizeof(node));
if(temp->next==(*first))
*last=newnode;
newnode->item=newitem;
newnode->next=temp->next;
temp->next=newnode;
}
}

void delet(node **first,node **last)


{
node *temp;
node *prev;
int target;
printf("\n Data to be deleted:");
scanf("%d",&target);
if(*first==NULL)
printf("\n List is empty");
else if((*first)->item==target)
{
if((*first)->next==*first)
*first=*last=NULL;
else
{
*first=(*first)->next;
(*last)->next=*first;
printf("\n Circular list\n");
display(*first,*last);
}
}
else
{
temp=*first;
prev=NULL;
while((temp->next!=(*first))&&((temp->item)!=target))
{
prev=temp;
temp=temp->next;
}
if(temp->item!=target)
{
printf("\n Element not found");
}
else
{
if(temp==*last)
*last=prev;
prev->next=temp->next;
printf("\n CIRCULAR LIST");
display(*first,*last);
}
}
}

void main()
{
node *start,*end;
int choice;
clrscr();
printf("\n CIRCULAR LINKED LIST");
printf("\n --------------------");
do
{
choice=menu();
switch(choice)
{
case 1:
printf("\n Type -999 to stop");
start=create(&end);
printf("\n Circular list\n");
display(start,end);
continue;

case 2:
insert(&start,&end);
printf("\n Circular list \n");
display(start,end);
continue;

case 3:
delet(&start,&end);
continue;
default:
printf("\n End");
}
}while(choice!=4);
}
Sample Input and Output

CIRCULAR LINKED LIST


---------------------------------
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:1
Type -999 to stop
Enter the data:10
20
30
-999
Circular list

10 20 30
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:2
Enter the new item:40
Position of insertion:2
Circular list
10 40 20 30
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:3
Data to be deleted:20
Circular List
10 40 30
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:3

Data to be deleted:60
Element not found

CPP Program To Implement Circular Linked List:

//Circular Linked List in CPP


#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
#define null 0
struct node
{
int info;
struct node *link;
public:
}*start,*last;
void main()
{
int ch,n,m,position,i;
void create(int);
void addat(int);
void addbt(int,int);
void del(int);
void disp();
last=null;
clrscr();
while(1)
{
cout<<"\n\nMAIN MENU";
cout<<"\n\n1.create\n2.addat\n3.addbt\n4.del\n5.disp\n6.exit";
cout<<"\n\nENTER YOUR CHOICE : ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n\nENETER NO OF ITC : ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\n\nENTER THE ELEMENT : ";
cin>>m;
create(m);
}break;
case 2:
cout<<"\n\nENTER THE ELEMENT : ";
cin>>m;
addat(m);
break;
case 3:
cout<<"\n\nENTER THE ELEMENT : ";
cin>>m;
cout<<"\n\nENTER THE POSITION : ";
cin>>position;
addbt(m,position);
break;
case 4:
if(last==null)
{
cout<<"\n\nLIST IS EMPTY";
continue;
}
cout<<"\n\nENTER THE ELEMENT FOR DELETE : ";
cin>>m;
del(m);
break;
case 5:
disp();
break;
case 6:
exit(0);
break;
default:
cout<<endl<<endl<<"wrong choice";
}
}
}
void create(int data)
{
struct node *q,*tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=null;
if(last==null)
{
last=tmp;
tmp->link=last;
}
else
{
tmp->link=last->link;
last->link=tmp;
last=tmp;
}
return;
}
void addat(int data)
{

struct node *q,*tmp;


tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=data;
tmp->link=last->link;
last->link=tmp;
}
void addbt(int data,int pos)
{
struct node *tmp,*q;
int i;
q=last->link;;
for(i=0;i<pos-1;i++)
{
q=q->link;
if(q==last->link)
{
cout<<"\n\nthere r lessthan "<<pos<<"elements ";
return;
}
}
tmp=(struct node *)malloc(sizeof(struct node));
tmp->link=q->link;
tmp->info=data;
q->link=tmp;
if(q==last)
last=tmp;
}
void del(int data)
{
struct node *tmp,*q;
if(last->link==last&&last->info==data)
{
tmp=last;
last=null;
free(tmp);
cout<<"\n\nElement is "<<data<" deleted ";
return;
}
q=last->link;
if(q->info==data)
{
tmp=q;
last->link=q->link;
free(tmp);
cout<<"\n\nElement is "<<data<"deleted ";
return;
}
while(q->link!=last)
{
if(q->link->info==data)
{
tmp=q->link;
q->link=tmp->link;
free(tmp);
cout<<"\n\nElement is "<<data<<" deleted ";
return;
}
q=q->link;
}
if(q->link==last)
{
if(q->link->info==data)
{
tmp=last;
last=q;
last->link=tmp->link;
free(tmp);
cout<<"\n\nElement is "<<data<<" deleted ";
return;
}
}

cout<<"\n\nThe element not found ";

}
void disp()
{
struct node *q;
if(last==null)
{
cout<<"\n\nlist isdempty";
return;
}q=last->link;
cout<<endl;
while(q!=last)
{
cout<<q->info<<" ";
q=q->link;
}
cout<<last->info;
return;
}
Sample Input and output

CIRCULAR LINKED LIST


---------------------------------
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:1
Type -999 to stop
Enter the data:10
20
30
-999
Circular list

10 20 30
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:2
Enter the new item:40
Position of insertion:2
Circular list
10 40 20 30
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:3
Data to be deleted:20
Circular List
10 40 30
MIAN NENU
1.CREATE
2.INSERT
3.DELETE
4.EXIT
Enter your choice:3
Data to be deleted:60
Element not found

Adding Two Polynomial Equations:


Algorithm Steps:
Step 1: Read the cofficient and power of the polynomial euation one and assign it's elements into a
linked list.

step 2: Read the cofficient and power of the polynomial quation two and assign it's elements into a
linked list.

step 3: Sorting the first polynomial in power order wise.

Compare the first node's power with next nodes power,if second node's power is greate than
first Node then swap.Repeat the process until we get the proper order.

Step 4: Sorting the second polynomial in power order wise.

Compare the first node's power with next nodes power,if second node's power is greate than
first Node then swap.Repeat the process until we get the proper order.

Step 5 :Add the two polynomial.


If power part of the two list is qual than add the coffiecient
C Program To Add two Polynomial equations

CPP Program To Add two Polynomial equations

C Program To Add Two Polynomial Equations :

/**PROGRAM TO ADD TWO POLYNOMIALS**/


#include<stdio.h>
#include<conio.h>
struct barbie
{
int coff;
int pow;
struct barbie *link;
}*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2;
typedef struct barbie bar;
int temp1,temp2;

void main()
{

void create(void);
void display(void);
void polyaddtion(void);
void sorting(void);
clrscr();

printf("\n\nEnrter the elements of the first poly");


node = (bar *) malloc(sizeof (bar));
start1=node;
if (start1==NULL)
{
printf("\n\nUnable to create memory.");
getch();
exit();
}
create();

printf("\n\nEnrter the elements of the second poly :");


node = (bar *) malloc(sizeof (bar));
start2=node;
if (start2==NULL)
{
printf("\n\nUnable to create memory.");
getch();
exit();
}
create();
clrscr();
//printing the elements of the lists
printf("\n\nThe elements of the poly first are :");
ptr=start1;
display();

printf("\n\nThe elements of the poly second are :");


ptr=start2;
display();

printf("\n\nThe first sorted list is :");


ptr=start1;
sorting();
ptr=start1;
display();

printf("\n\nThe second sorted list is :");


ptr=start2;
sorting();
ptr=start2;
display();

printf("\n\nThe sum of the two lists are :");


polyaddtion();
ptr=start3;
display();

getch();

}
/*-----------------------------------------------------------------------------*/
void create()
{
char ch;
while(1)
{
printf("\n\nEnter the coff and pow :");
scanf("%d%d",&node->coff,&node->pow);
if (node->pow==0 )
{
ptr=node;
node=(bar *)malloc(sizeof(bar));
node=NULL;
ptr->link=node;
break;
}

printf("\n\nDo u want enter more coff ?(y/n)");


fflush(stdin);
scanf("%c",&ch);
if (ch=='n' )
{
ptr=node;
node=(bar *)malloc(sizeof(bar));
node=NULL;
ptr->link=node;
break;
}
ptr=node;
node=(bar *)malloc(sizeof(bar));
ptr->link=node;
}
}
/*-------------------------------------------------------------------------*/
void display()
{ int i=1;

while(ptr!=NULL )
{
if(i!=1)
printf("+ ");
printf(" %dx^%d ",ptr->coff,ptr->pow);
ptr=ptr->link;
i++;
}
//printf(" %d^%d",ptr->coff,ptr->pow);
}
/*---------------------------------------------------------------------------*/
void sorting()
{
for(;ptr->coff!=NULL;ptr=ptr->link)
for(ptr2=ptr->link;ptr2->coff!=NULL;ptr2=ptr2->link)
{
if(ptr->pow>ptr2->pow)
{
temp1=ptr->coff;
temp2=ptr->pow;
ptr->coff=ptr2->coff;
ptr->pow=ptr2->pow;
ptr2->coff=temp1;
ptr2->pow=temp2;

}
}
}
/*---------------------------------------------------------------------------*/
void polyaddtion()
{
node=(bar *)malloc (sizeof(bar));
start3=node;

ptr1=start1;
ptr2=start2;

while(ptr1!=NULL && ptr2!=NULL)


{
ptr=node;
if (ptr1->pow > ptr2->pow )
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
}
else if ( ptr1->pow < ptr2->pow )
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list A
}
else
{
node->coff=ptr2->coff+ptr1->coff;
node->pow=ptr2->pow;
ptr1=ptr1->link; //update ptr list A
ptr2=ptr2->link; //update ptr list B

node=(bar *)malloc (sizeof(bar));


ptr->link=node; //update ptr list C
}//end of while

if (ptr1==NULL) //end of list A


{
while(ptr2!=NULL)
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
ptr=node;
node=(bar *)malloc (sizeof(bar));
ptr->link=node; //update ptr list C
}
}

else if (ptr2==NULL) //end of list B


{
while(ptr1!=NULL)
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list B
ptr=node;
node=(bar *)malloc (sizeof(bar));
ptr->link=node; //update ptr list C
}
}
node=NULL;
ptr->link=node;
}

SAMPLE INPUT AND OUTPUT:

Enter the element of the first poly


Enter the coff and pow : 3 2
Do u want enter more coff ?(y/n)y
Enter the coff and pow :5 1
Do u want enter more coff ?(y/n)n
Enter the elements of the second poly:
Enter the coff and pow :4 2
Do u want enter more coff ?(y/n)y
Enter the coff and pow :4 2
The elements of the poly first are : 3x^2 + 5x^1
The elements of the poly first are : 4x^2 + 4x^1
The first sorted list is : 5X^1 + 3X^2
The sacond sorted list is : 4X^1 + 4x^2
The sum of the two lists are : 9X^1 + 7X^2

CPP Program To Add Two Polynomial Equations :


/**PROGRAM TO ADD TWO POLYNOMIALS**/
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
class PolyAdd
{
public:
struct barbie
{
int coff;
int pow;
struct barbie *link;
}*ptr,*start1,*node,*start2,*start3,*ptr1,*ptr2;
typedef struct barbie bar;
int temp1,temp2;
void create(void);
void display(void);
void polyaddtion(void);
void sorting(void);
};

/*-----------------------------------------------------------------------------*/
void PolyAdd :: create()
{
char ch;
while(1)
{
cout<<"\n\nEnter the coff and pow :";
//scanf("%d%d",&node->coff,&node->pow);
cin>>node->coff;
cin>>node->pow;
if (node->pow==0 )
{
ptr=node;
node=(bar *)malloc(sizeof(bar));
node=NULL;
ptr->link=node;
break;
}

cout<<"\n\nDo u want enter more coff ?(y/n)";


fflush(stdin);
//scanf("%c",&ch);
cin>>ch;
if (ch=='n' )
{
ptr=node;
node=(bar *)malloc(sizeof(bar));
node=NULL;
ptr->link=node;
break;
}
ptr=node;
node=(bar *)malloc(sizeof(bar));
ptr->link=node;
}
}
/*-------------------------------------------------------------------------*/
void PolyAdd :: display()
{ int i=1;

while(ptr!=NULL )
{
if(i!=1)
cout<<"+ ";
cout<<" "<<ptr->coff<<"x^"<<ptr->pow<<" ";
ptr=ptr->link;
i++;
}
//printf(" %d^%d",ptr->coff,ptr->pow);
}
/*---------------------------------------------------------------------------*/
void PolyAdd :: sorting()
{
for(;ptr->coff!=NULL;ptr=ptr->link)
for(ptr2=ptr->link;ptr2->coff!=NULL;ptr2=ptr2->link)
{
if(ptr->pow>ptr2->pow)
{
temp1=ptr->coff;
temp2=ptr->pow;
ptr->coff=ptr2->coff;
ptr->pow=ptr2->pow;
ptr2->coff=temp1;
ptr2->pow=temp2;

}
}
}
/*---------------------------------------------------------------------------*/
void PolyAdd :: polyaddtion()
{
node=(bar *)malloc (sizeof(bar));
start3=node;

ptr1=start1;
ptr2=start2;

while(ptr1!=NULL && ptr2!=NULL)


{
ptr=node;
if (ptr1->pow > ptr2->pow )
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
}
else if ( ptr1->pow < ptr2->pow )
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list A
}
else
{
node->coff=ptr2->coff+ptr1->coff;
node->pow=ptr2->pow;
ptr1=ptr1->link; //update ptr list A
ptr2=ptr2->link; //update ptr list B

}
node=(bar *)malloc (sizeof(bar));
ptr->link=node; //update ptr list C
}//end of while

if (ptr1==NULL) //end of list A


{
while(ptr2!=NULL)
{
node->coff=ptr2->coff;
node->pow=ptr2->pow;
ptr2=ptr2->link; //update ptr list B
ptr=node;
node=(bar *)malloc (sizeof(bar));
ptr->link=node; //update ptr list C
}
}

else if (ptr2==NULL) //end of list B


{
while(ptr1!=NULL)
{
node->coff=ptr1->coff;
node->pow=ptr1->pow;
ptr1=ptr1->link; //update ptr list B
ptr=node;
node=(bar *)malloc (sizeof(bar));
ptr->link=node; //update ptr list C
}
}
node=NULL;
ptr->link=node;
}

/*------------------------------------------------------------------------------------*/

void main()
{
PolyAdd obj;
clrscr();
cout<<"\n\nEnrter the elements of the first poly";
obj.node = (bar *) malloc(sizeof (bar));
obj.start1=obj.node;
if (obj.start1==NULL)
{
cout<<"\n\nUnable to create memory.";
getch();
exit(0);
}
obj.create();

cout<<"\n\nEnrter the elements of the second poly :";


obj.node = (bar *) malloc(sizeof (bar));
obj.start2=obj.node;
if (obj.start2==NULL)
{
cout<<"\n\nUnable to create memory.";
getch();
exit(0);
}
obj.create();
clrscr();
//printing the elements of the lists
cout<<"\n\nThe elements of the poly first are :";
obj.ptr=obj.start1;
obj.display();

cout<<"\n\nThe elements of the poly second are :";


obj.ptr=obj.start2;
obj.display();

cout<<"\n\nThe first sorted list is :";


obj.ptr=obj.start1;
obj.sorting();
obj.ptr=obj.start1;
obj.display();
cout<<"\n\nThe second sorted list is :";
obj.ptr=obj.start2;
obj.sorting();
obj.ptr=obj.start2;
obj.display();

cout<<"\n\nThe sum of the two lists are :";


obj.polyaddtion();
obj.ptr=obj.start3;
obj.display();

getch();

}
SAMPLE INPUT AND OUTPUT:

Enter the element of the first poly


Enter the coff and pow : 3 2
Do u want enter more coff ?(y/n)y
Enter the coff and pow :5 1
Do u want enter more coff ?(y/n)n
Enter the elements of the second poly:
Enter the coff and pow :4 2
Do u want enter more coff ?(y/n)y
Enter the coff and pow :4 2
The elements of the poly first are : 3x^2 + 5x^1
The elements of the poly first are : 4x^2 + 4x^1
The first sorted list is : 5X^1 + 3X^2
The sacond sorted list is : 4X^1 + 4x^2
The sum of the two lists are : 9X^1 + 7X^2

Implementation Of Binary Search :


Binary search:
Definition:
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found or the interval is empty.
Advantages:

1. It is faster than linear search.

2. It is astounding for large numbers.


Disadvantages:

1. Binary search can interact poorly with the memory hierarchy (i.e. caching), because of its
random-access nature.
2. Before searching the elements shorting is necessary.It take some additional overhead to
machine.
Analysis of the Binary sort:
1. Worest case performance O(log n)
2. Best case performance O(1)
3. Average case performance O( log n)
Algorithm steps:

Step 1: Read the elements of the list.

Step 2: Sort the input list.

Step 3: Find the mid value.

Step 4: Look at the element in the middle. If the key is equal to that, the search is finished.

Step 5: If the key is less than the middle element, do a binary search on the first half.

Step 6: If it's greater, do a binary search of the second half.


C Program To Implement Binary Search

CPP Program To Implement Binary Search


#include<stdio.h>
#include<conio.h>
void main()
{
int a[25],i,j,temp,s,n,low,mid,high;
clrscr();
printf("\nEnter the Limilt : ");
scanf("%d",&n);
printf("\n\nEnter the elements\n");
for(i=0;i<n;i++)
{

scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n\nSorted list");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
printf("\n\nEnter the elements to be searched : ");
scanf("%d",&s);
high=n-1;
low=0;
while(low<=high)
{
mid=(low+high)/2;
if(s>a[mid])
low=mid+1;
else if(s<a[mid])
high=mid-1;
else if(s==a[mid])
{
printf("\n\nThe element %d is found",s);
getch();
exit(0);
}
}
printf("\n\nThe element %d is not found",s);
getch();
}

SAMPLE INPUT AND OUTPUT:

Enter the elements


5
4
3
2
1
Sorted list
1
2
3
4
5
Enter the element to be searched : 5
The element 5 is found.

CPP Program To Implement Binary Search :

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class BinarySearch
{
int a[25],n;
public:
void getdata();
void sorting();
void binarysearch();
};

void BinarySearch :: getdata()


{
clrscr();
cout<<endl<<endl<<"***BINARY SEARCH***";
cout<<endl<<endl<<"Enter the Limilt : ";
cin>>n;
cout<<endl<<endl<<"Enter the Elements\n";
for(int i=0;i<n;i++)
cin>>a[i];
}
void BinarySearch :: sorting()
{
int temp;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

}
void BinarySearch :: binarysearch()
{
int high,low,mid,s;
cout<<endl<<endl<<"Enter the elements to be searched : ";
cin>>s;
high=n-1;
low=0;
while(low<=high)
{
mid=(low+high)/2;
if(s>a[mid])
low=mid+1;
else if(s<a[mid])
high=mid-1;
else if(s==a[mid])
{
cout<<endl<<endl<<"The element "<<s<<" is found";
getch();
exit(0);
}
}
cout<<endl<<endl<<"The element "<<s<<" is not found";

}
void main()
{
BinarySearch obj;
obj.getdata();
obj.sorting();
obj.binarysearch();
getch();
}

SAMPLE INPUT AND OUTPUT:

Enter the elements


5
4
3
2
1

Sorted list
1
2
3
4
5

Enter the element to be searched : 5

The element 5 is found.

Implementation Postfix Expression Evaluation:


Postfix Evaluation:

Infix Expression :

Any expression in the standard form like "2*3-4/5" is an Infix( Inorder) expression.

Postfix Expression :

The Postfix ( Postorder) form of the above expression is "23*45/-".

Postfix Evaluation :

In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+.
Algorithm Steps:
 Scan the Postfix string from left to right.
 Initialize an empty stack.
 If the scanned character is an operand, add it to the stack. If the scanned character is an
operator, there will be atleast two operands in the stack.
 If the scanned character is an Operator, then we store the top most element of the stack(top
Stack) in a variable temp. Pop the stack. Now evaluate top Stack(Operator)temp. Let the
result of this operation be ret Val. Pop the stack and Push ret Val into the stack.
Repeat this step till all the characters are scanned.
 After all characters are scanned, we will have only one element in the stack. Return top
Stack.
C Program To Implement Postfix Expression Evaluation

CPP Program To Implement Postfix Expression Evaluation

C Program To Implement Postfix Expression Evaluation :


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
#define MAX 50

struct postfix
{
int stack[MAX];
int top,nn;
char *s;
};

void initpostfix(struct postfix *);


void setexpr(struct postfix *,char *);
void push(struct postfix *,int);
int pop(struct postfix *);
void calculate(struct postfix *);
void show(struct postfix);
void main()
{
struct postfix q;
char expr[MAX];
clrscr();
initpostfix(&q);
printf("\n ________________________________");
printf("\n EVALUATION OF POSTFIX EXPRESSION");
printf("\n --------------------------------");
printf("\n DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS");
printf("\n Enter two single digit numbers and a operator\n");
printf("\n Enter an expression:");
gets(expr);
setexpr(&q,expr);
calculate(&q);
show(q);
getch();
}

void initpostfix(struct postfix *p)


{
p->top=-1;
}

void setexpr(struct postfix *p,char *str)


{
p->s=str;
}

void push(struct postfix *p,int item)


{
if(p->top==MAX-1)
printf("\n Stack is full");
else
{
p->top++;
p->stack[p->top]=item;
}
}
int pop(struct postfix *p )
{
int data;
if(p->top==-1)
{
printf("Stack is empty");
return NULL;
}
data=p->stack[p->top];
p->top--;
return(data);
}

void calculate(struct postfix *p)


{
int n1,n2,n3;
while(*(p->s))
{
if(isdigit(*(p->s)))
{
p->nn=*(p->s)-'0';
push(p,p->nn);
}
else
{
n1=pop(p);
n2=pop(p);
switch(*(p->s))
{
case '+':
n3=n2+n1;
break;
case '-':
n3=n2-n1;
break;
case '*':
n3=n2*n1;
break;
case '/':
n3=n2/n1;
break;
case '%':
n3=n2%n1;
break;
default:
printf("\n Unknown operator");
getch();
exit(0);
}
push(p,n3);
}
p->s++;
}
}

void show(struct postfix p)


{
p.nn=pop(&p);
printf("\n Result is %d",p.nn);
}

SAMPLE INPUT AND OUTPUT:


________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:23*
Result is 6

________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:57-
Result is -2
________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:45%
Result is 4

CPP Program To Implement Postfix Expression Evaluation :

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
#define MAX 50
class PostFix
{
public:
struct postfix
{
int stack[MAX];
int top,nn;
char *s;
}q;
void initpostfix(struct postfix *);
void setexpr(struct postfix *,char *);
void push(struct postfix *,int);
int pop(struct postfix *);
void calculate(struct postfix *);
void show(struct postfix);
};

void PostFix :: initpostfix(struct postfix *p)


{
p->top=-1;
}
void PostFix :: setexpr(struct postfix *p,char *str)
{
p->s=str;
}

void PostFix :: push(struct postfix *p,int item)


{
if(p->top==MAX-1)
cout<<"\n Stack is full";
else
{
p->top++;
p->stack[p->top]=item;
}
}

int PostFix :: pop(struct postfix *p )


{
int data;
if(p->top==-1)
{
cout<<"\nStack is empty";
return NULL;
}
data=p->stack[p->top];
p->top--;
return(data);
}

void PostFix :: calculate(struct postfix *p)


{
int n1,n2,n3;
while(*(p->s))
{
if(isdigit(*(p->s)))
{
p->nn=*(p->s)-'0';
push(p,p->nn);
}
else
{
n1=pop(p);
n2=pop(p);
switch(*(p->s))
{
case '+':
n3=n2+n1;
break;
case '-':
n3=n2-n1;
break;
case '*':
n3=n2*n1;
break;
case '/':
n3=n2/n1;
break;
case '%':
n3=n2%n1;
break;
default:
cout<<"\n Unknown operator";
getch();
exit(0);
}
push(p,n3);
}
p->s++;
}
}

void PostFix :: show(struct postfix p)


{
p.nn=pop(&p);
cout<<"\n Result is "<<p.nn;
}
void main()
{
PostFix obj;
char expr[MAX];
clrscr();
obj.initpostfix(&obj.q);
cout<<"\n ________________________________";
cout<<"\n EVALUATION OF POSTFIX EXPRESSION";
cout<<"\n --------------------------------";
cout<<"\n DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS";
cout<<"\n Enter two single digit numbers and a operator\n";
cout<<"\n Enter an expression:";
gets(expr);
obj.setexpr(&obj.q,expr);
obj.calculate(&obj.q);
obj.show(obj.q);
getch();
}

SAMPLE INPUT AND OUTPUT:


________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:23*
Result is 6

________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:57-
Result is -2
________________________________
EVALUATION OF POSTFIX EXPRESSION
---------------------------------------------
DON'T GIVE SPACE INBETWEEN NUMBERS OR OPERATORS
Enter two single digit numbers and a operator
Enter an expression:45%
Result is 4

Implementation Of Bubble Sort:


Sorting:
Sorting algorithm is an algorithm that puts elements of a list in a certain order . The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.

Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange,,selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.

Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc


External sorting:

It takes the place in secondary memory of a computer,Since the number of objects to be


stored is too large to fit in main memory

Eg:Merge sort,Multiway Merge,Polyphase merge.


Bubble Sort:

Bubble Sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be
sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass
through the list is repeated until no swaps are needed, which indicates that the list is sorted. The
algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it
only uses comparisons to operate on elements, it is a comparison sort .
Analysis of bubble sort:

Worest case performance O(n2)

Best case performance O(n)

Average case performance O(n2)

Advantages:

It is very simple to implement.


Disadvantages:
If list is very large it take long time to evaluate.
Algorithm steps:
Step 1: Read the input list size.

Step 2: Read the list elements.

Step 3: Assign count =0

Step 4: Repeat the loop until count less than list size.(for n-1 passes)

i) Assign inner_count=count+1

ii) Repeat the loop inner_count less than list size (for arrange the
1) If list [count]> list [inner_count] (check element value )

2) temp = list [count]

3) list [count]=list[inner_count]

4) a[inner_count]=temp
C Program To Implement Bubble Sort

CPP Program To Implement Bubble Sort

C Program To Implement Bubble Sort :

#include<stdio.h>
void bubble(int a[],int n);
int i,j,temp,a[25],n;
void main()
{
clrscr();
printf("\n\nEnter how many numbers you want to sort\n\n");
scanf("%d",&n);
printf("\nEnter the numbers \n");
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
bubble(a,n);
printf("\n\nFinal sorted list is ");
for (i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
void bubble(int a[],int n)
{
int k;
for(i=0;i<n-1;i++)
{
printf("\n\n PASS->%d ",i+1);
for(j=i+1;j<=n-1;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
for(k=0;k<n;k++)
printf("%d ",a[k]);
printf("\n");
}
}
SAMPLE INPUT AND OUTPUT:

Enter how many elements you want to sort


5
Enter the numbers
5
4
3
2
1
PASS->1 15432
PASS->2 12543
PASS->3 12354
PASS->4 12345
Final sorted list is 1 2 3 4 5

CPP Program To Implement Bubble Sort :

#include<iostream.h>
#include<conio.h>
class BubbleSort
{
int a[25],len;
public:
void getdata();
void bubblesort();
void display();
};
void BubbleSort :: getdata()
{
cout<<endl<<endl<<"***BUBBLE SORT***";
cout<<endl<<endl<<"Enter the Limit : ";
cin>>len;
cout<<endl<<endl<<"Enter the numbers"<<endl;
for(int i=0;i<len;i++)
cin>>a[i];
}
void BubbleSort :: bubblesort()
{
int k,temp;
cout<<endl<<endl<<"***BUBBLE SORT PROCESS***";
for(int i=0;i<len-1;i++)
{
cout<<endl<<endl<<"PASS->"<<"("<<i+1<<")";
for(int j=i+1;j<=len-1;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
for(k=0;k<len;k++)
cout<<" "<<a[k]<<" ";
}
cout<<endl<<"*************************";
}

void BubbleSort :: display()


{
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
}
void main()
{
BubbleSort obj;
clrscr();
obj.getdata();
clrscr();
cout<<endl<<endl<<"BEFORE SORTING "<<endl<<endl;
obj.display();
obj.bubblesort();
cout<<endl<<endl<<"AFTER SORTING "<<endl<<endl;
obj.display();
getch();
}

SAMPLE INPUT AND OUTPUT:


Enter how many elements you want to sort
5
Enter the numbers
5
4
3
2
1
PASS->1 15432
PASS->2 12543
PASS->3 12354
PASS->4 12345
Final sorted list is 1 2 3 4 5

Implementation Of Selection Sort:


Sorting algorithm is an algorithm that puts elements of a list in a certain order . The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.

Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange,,selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.

Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc


External sorting:
It takes the place in secondary memory of a computer,Since the number of objects to be stored is
too large to fit in main memory.

Eg:Merge sort,Multiway Merge,Polyphase merge.


Selection sort:
Selection sort is a sorting algorithm, specifically an in-place comparison sort . It has O(n2)
complexity, making it inefficient on large lists, and generally performs worse than the similar
insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over
more complicated algorithms in certain situations.

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up
from left to right and is found at the beginning, and the sublist of items remaining to be sorted,
occupying the remainder of the array.
It have n(n-1) comparisios.
Analysis of selection sort:

Worest case performance O(n2)

Best case performance O(n2)

Average case performance O(n2)


Advantages:
1. It is very simple to implement.
Disadvantages:

1. If list is very large it takes long time to evaluate.

Algorithm Steps:
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)
C Program To Implement Selection Sort

CPP Program To Implement Selection Sort

C Program To Implement Selection Sort :

#include<stdio.h>
#include<conio.h>
int n,i=0,j=0,t=0,k=0,a[30];
void main()
{
clrscr();
printf("\nEnter how many numbers you want to sort\n");
scanf("%d",&n);
printf("\nEntyer the numbers \n");
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for (i=1;i<n;i++)
{
printf("\n\nPASS %d-->",i);
t=a[i];
for(j=i-1;((j>=0)&&(t<a[j]));j--)
a[j+1]=a[j];
a[j+1]=t; //j decreases
for(k=0;k<n;k++)
printf("%d ",a[k]);
}
printf("\n\nThe sorted list is : ");
for (j=0;j<n;j++)
printf("%d ",a[j]);
getch();
}

Sample Input and Output:

Enter how many elements you want to sort


5
Enter the numbers
5
4
3
2
1
PASS->1 15432
PASS->2 12543
PASS->3 12354
PASS->4 12345
Final sorted list is 1 2 3 4 5

CPP Program To Implement Selection Sort :

#include<iostream.h>
#include<conio.h>
class SelSort
{
int a[25],len;
public:
void getdata();
void selectionsort();
void display();
};
void SelSort :: getdata()
{
cout<<endl<<endl<<"***SELECTION SORT***";
cout<<endl<<endl<<"Enter the Limit : ";
cin>>len;
cout<<endl<<endl<<"Enter the Elements"<<endl;
for(int i=0;i<len;i++)
cin>>a[i];
}

void SelSort :: selectionsort()


{
int t;
cout<<endl<<endl<<"***SELECTION SORT PROCESS***";
for (int i=1;i<len;i++)
{
cout<<endl<<endl<<"PASS->"<<"("<<i<<")";
t=a[i];
for(int j=i-1;((j>=0)&&(t<a[j]));j--)
a[j+1]=a[j];
a[j+1]=t; //j decreases
for(int k=0;k<len;k++)
cout<<" "<<a[k]<<" ";
}
cout<<endl<<"*************************";
}
void SelSort :: display()
{
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
}
void main()
{
clrscr();
SelSort obj;
obj.getdata();
clrscr();
cout<<endl<<endl<<"BEFORE SORTING "<<endl<<endl;
obj.display();
obj.selectionsort();
cout<<endl<<endl<<"AFTER SORTING "<<endl<<endl;
obj.display();
getch();
}

Sample Input and Output:

Enter how many elements you want to sort


5
Enter the numbers
5
4
3
2
1
PASS->1 15432
PASS->2 12543
PASS->3 12354
PASS->4 12345
Final sorted list is 1 2 3 4 5

Implementation Of Insertion Sort:


Sorting:
Sorting algorithm is an algorithm that puts elements of a list in a certain order . The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.

Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange,,selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.

Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc


External sorting:

It takes the place in secondary memory of a computer,Since the number of objects to be stored is
too large to fit in main memory

Eg:Merge sort,Multiway Merge,Polyphase merge.


Insertion Sort:
Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is
built one entry at a time. It is much less efficient on large lists than more advanced algorithms such
as quicksort , heapsort, or merge sort.
(or)

Insertion sorts works by taking elements from the list one by one and inserting them in their current
position into a new sorted list.

Insertion sort consists of N-1 passes.

Insertion Sort Provides Several Advantages:


 Simple implementation
 Efficient for (quite) small data sets
 Adaptive, i.e. efficient for data sets that are already substantially sorted: the time complexity
is O( n + d), where d is the number of inversions
 More efficient in practice than most other simple quadratic (i.e. O ( n 2)) algorithms such as
selection sort or bubble sort: the average running time is n 2/4, and the running time is linear
in the best case
 Stable, i.e. does not change the relative order of elements with equal keys
 In-place , i.e. only requires a constant amount O(1) of additional memory space
 Online , i.e. can sort a list as it receives it
Limitations of insertion sort:

It is relatively efficient for small lists and mostly- sorted list.

It is expensive because of shifting all following elements by one.

Analysis of insertion sort:

Worest case performance O(n2)

Best case performance O(n)

Average case performance O(n2)


Algorithm steps:
Step 1: Read the input list size.

Step 2: Read the list elements.

step 3: pass=1

step 4: Repeat the following steps until pass reach size-1 (for N-1 passes)

i) key=list[Pass]

ii) swap=pass-1

iii) Repeat the follwoing steps if this condition is true list[swap]>key and
swap >= 0.(for comparision).

a) list [sawp+1]=list[swap ]

b) swap--
iv) list [swap+1]

C Program To Implement Insertion Sort

CPP Program To Insertion Sort

C Program To Implement Insertion Sort :


#include <stdio.h>
#include<conio.h>

void insertion_sort(int x[],int length)


{
int key,i,j;
for(j=1;j<length;j++)
{
key=x[j];
i=j-1;
while(x[i]>key && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}

void main()
{
void insertion_sort(int [],int);
int A[100];
int x=0,n=0;
clrscr();
printf("******INSERTION SORT******");
printf("\n\nENTER THE LIMIT : ");
scanf("%d",&n);
printf("\n\nENTER THE ELEMENTS ONE BY ONE\n\n");
for(x=0;x<n;x++)
scanf("%d",&A[x]);
printf("\n\nNON SORTED LIST\n\n");
for(x=0;x<n;x++)
{
printf("\n%d",A[x]);
}
insertion_sort(A,n);
printf("\n\nSORTED LIST\n\n");
for(x=0;x<n;x++)
{
printf("\n%d",A[x]);
}
getch();
}
SAMPLE INPUT AND OUTPUT:

ENTER THE LIMIT : 5


ENTER THE ELEMENTS ONE BY ONE
5
4
3
2
1
SORTED LIST
1
2
3
4
5

CPP Program To Implement Insertion Sort :

#include <iostream.h>
#include <conio.h>
class InsertionSort
{
public:
void insertion_sort(int [],int);
};

void InsertionSort :: insertion_sort(int x[],int length)


{
int key,i;
for(int j=1;j<length;j++)
{
key=x[j];
i=j-1;
while(x[i]>key && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}

void main()
{
int A[100],x,n;
InsertionSort q;
clrscr();
cout<<endl<<endl<<"******INSERTION SORT******";
cout<<endl<<endl<<"Enter the limit : ";
cin>>n;
cout<<"\n\nEnter the elements\n\n";
for(x=0;x<n;x++)
cin>>A[x];
cout<<endl<<endl<<"NON SORTED LIST\n";
for(x=0;x<n;x++)
{
cout<<A[x]<<endl;
}
q.insertion_sort(A,n);
cout<<endl<<endl<<"SORTED LIST\n";
for(x=0;x<n;x++)
{
cout<<A[x]<<endl;
}
getch();
}
SAMPLE INPUT AND OUTPUT:

ENTER THE LIMIT : 5

ENTER THE ELEMENTS ONE BY ONE

5
4
3
2
1
SORTED LIST
1
2
3
4
5

Implementation Of Shell Sort:


Sorting:
Sorting algorithm is an algorithm that puts elements of a list in a certain order . The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.

Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange,,selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.

Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc


External sorting:

It takes the place in secondary memory of a computer,Since the number of objects to be stored is
too large to fit in main memory.

Eg:Merge sort,Multiway Merge,Polyphase merge.


Shell sort:
Shell sort is a sorting algorithm that is a generalization of insertion sort, with two observations:
 insertion sort is efficient if the input is "almost sorted", and
 insertion sort is typically inefficient because it moves values just one position at a time.
Shellsort is one of the oldest sorting algorithms, named after its inventor D.L. Shell (1959) . It is
fast, easy to understand and easy to implement. However, its complexity analysis is a little more
sophisticated.
Analysis of the shell sort:
Worest case performance O(n2)

Best case performance O(n log n)

Average case performance O(n1.5)


Advantages of shell sort:
1. It is one of the fastest algorithms for sorting small number of elements.

2. It requires relatively small amounts of memory.


Alogrithm steps:
Step 1:

The whole array is first fragmented into K segments, where K is preferably a prime number.

Step 2:

Now the whole are is partially sorted.

Step 3:

The value of K is reduced which increase the size of each segment and reduce the no of
segments.

Step 4:

The next value of K is chosen so that it is relatively prime to its previous value.

Step 5:

Repeat the step 4 until K=1,at which the array is sorted.

The insertion sort is applied in each segment, so each successive segment is partially sorted.
C Program To Implement Shell Sort

CPP Program To Implement Shell Sort

C Program To Implement Shell Sort:

#include<stdio.h>
#include<conio.h>
void shell(int a[],int n);
int i,j,k,n,temp,array[25];
void main()
{
clrscr();
printf("\n SHELL SORT");
printf("\n **********");
printf("\n Enter the limit:");
scanf("%d",&n);
printf("\n Enter the elements\n\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
shell(array,n);
printf("\n Sorted list:");
for(i=0;i<n;i++)
printf("\n %d",array[i]);
getch();
}

void shell(int a[],int n)


{
for(i=(n+1)/2;i>=1;i/=2)
{
for(j=i;j<=n-1;j++)
{
temp=a[j];
k=j-i;
while(k>=0&&temp<a[k])
{
a[k+i]=a[k];
k=k-i;
}
a[k+i]=temp;
}
}
}

SAMPLE INPUT AND OUTPUT:

Enter the limit: 5


Enter the elements
5
4
3
2
1

Sorted list:

1
2
3
4
5

CPP Program To Implement Shell Sort:


#include<iostream.h>
#include<conio.h>
class ShellSort
{
public:
int i,j,k,n,temp,array[25];
void shell(int a[],int n);
};

void ShellSort :: shell(int a[],int n)


{
for(i=(n+1)/2;i>=1;i/=2)
{
for(j=i;j<=n-1;j++)
{
temp=a[j];
k=j-i;
while(k>=0&&temp<a[k])
{
a[k+i]=a[k];
k=k-i;
}
a[k+i]=temp;
}
}
}
void main()
{
clrscr();
ShellSort obj;
cout<<"\n SHELL SORT";
cout<<"\n **********";
cout<<"\n Enter the limit:";
cin>>obj.n;
cout<<"\n Enter the elements\n\n";
for(int j=0;j<obj.n;j++)
cin>>obj.array[j];
obj.shell(obj.array,obj.n);
cout<<"\n Sorted list : ";
for(int i=0;i<obj.n;i++)
cout<<"\n"<<obj.array[i];
getch();
}
SAMPLE INPUT AND OUTPUT:

Enter the limit: 5


Enter the elements
5
4
3
2
1

Sorted list:

1
2
3
4
5

Implementation Of Heap Sort:


Sorting:
Sorting algorithm is an algorithm that puts elements of a list in a certain order . The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.
Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange,,selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.

Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc


External sorting:

It takes the place in secondary memory of a computer,Since the number of objects to be stored is
too large to fit in main memory.

Eg:Merge sort,Multiway Merge,Polyphase merge.


Heap sort:
Heapsort (method) is a comparison-based sorting algorithm, and is part of the selection sort family.
Although somewhat slower in practice on most machines than a good implementation of quicksort,
it has the advantage of a worst-case Θ(n log n) runtime. Heapsort is an in-place algorithm, but is not
a stable sort.
In heap sort the array is interpreted as a binary tree. This method has 2 phases.

In phase 1, binary heap is constructed.

In phase 2, delete min routine is performed.

Analysis of the heap sort:


Worest case performance O(n log n)

Best case performance O(n log n)

Average case performance O(n log n)


Advantages of heap sort:
1.It is efficient for sorting large number of elements.

2.It has the advantages of worst case O(N log N) running time.
Limitations:

1. It is not a stable sort.

2. It requires more processing time


Alogrithm steps:
Step1: Read the size of the list
Step2: Read the elements of the list
Step3: Binary heap construction.
1) Structrue Property:
For any element in array position I,the left child is in position 2i,the right child is in
2i+1,(ie) the cell after the left child.
2) Heap Order Property:
The value in the parent node is smaller than or equal to the key value of any of its child
node.Build the heap,apply the heap order propery starting from the right. most non-leaf node at the
bottom level.
Step 4: Delete min routine is performed.

The array elements aer stored using deletemin operation,which gives the elements arranged in
descending order.
C Program To Implement Heap Sort

CPP Program To Implement Heap Sort

C Program To Implement Heap Sort:

#include<stdio.h>
#include<conio.h>

int hsort[25],n,i;

void adjust(int,int);
void heapify();

void main()
{
int temp;
clrscr();
printf("\n\t\t\t\tHEAP SORT");
printf("\n\t\t\t\t**** ****\n\n\n");
printf("\nenter no of elements:");
scanf("%d",&n);
printf("\nenter elements to be sorted\n\n");

for(i=1;i<=n;i++)
scanf("%d",&hsort[i]);
heapify();

for(i=n;i>=2;i--)
{
temp=hsort[1];
hsort[1]=hsort[i];
hsort[i]=temp;
adjust(1,i-1);
}

printf("\nSORTED ELEMENT\n\n");
for(i=1;i<=n;i++)
printf("%d\n",hsort[i]);
getch();
}

void heapify()
{
int i;
for(i=n/2;i>=1;i--)
adjust(i,n);
}
void adjust(int i,int n)
{
int j,element;
j=2*i;
element=hsort[i];
while(j<=n)
{
if((j<n)&&(hsort[j]<hsort[j+1]))
j=j++;
if(element>=hsort[j])
break;
hsort[j/2]=hsort[j];
j=2*j;
}
hsort[j/2]=element;
}
SAMPLE INPUT AND OUTPUT:

Enter No Of Elements:5
Enter Elements To Be Sorted
5
4
3
2
1
Sorted Element
1
2
3
4
5

CPP Program To Implement Heap Sort:

#include<iostream.h>
#include<conio.h>

int hsort[25],n,i;

void adjust(int,int);
void heapify();

void main()
{
int temp;
clrscr();
cout<<"\n\t\t\t\tHEAP SORT";
cout<<"\n\t\t\t\t**** ****\n\n\n";
cout<<"\nenter no of elements:";
cin>>n;
cout<<"\nenter elements to be sorted\n\n";

for(i=1;i<=n;i++)
cin>>hsort[i];
heapify();

for(i=n;i>=2;i--)
{
temp=hsort[1];
hsort[1]=hsort[i];
hsort[i]=temp;
adjust(1,i-1);
}

cout<<"\nSORTED ELEMENT\n\n";
for(i=1;i<=n;i++)
cout<<hsort[i]<<endl;
getch();
}

void heapify()
{
int i;
for(i=n/2;i>=1;i--)
adjust(i,n);
}
void adjust(int i,int n)
{
int j,element;
j=2*i;
element=hsort[i];
while(j<=n)
{
if((j<n)&&(hsort[j]<hsort[j+1]))
j=j++;
if(element>=hsort[j])
break;
hsort[j/2]=hsort[j];
j=2*j;
}
hsort[j/2]=element;
}

SAMPLE INPUT AND OUTPUT:

Enter No Of Elements:5
Enter Elements To Be Sorted
5
4
3
2
1
Sorted Element
1
2
3
4
5

Implementation Of Merge Sort:


Sorting:
Sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.

Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange, selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.


Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc
External sorting:

It takes the place in secondary memory of a computer,Since the number of objects to be stored is
too large to fit in main memory.

Eg:Merge sort,Multiway Merge,Polyphase merge.


Merge sort:

The most common algorithm used in external sorting is the mergesort.

This algorithm follows divide and conquer startegy.

i) Dividing Phase.

The problem is divided into smaller problem and solved recursively.

ii) Conquering Phase.

The partitioned array is merged together recursively.


Merge sort is an O(n log n) comparison-based sorting algorithm. In most implementations it is
stable, meaning that it preserves the input order of equal elements in the sorted output. It is an
example of the divide and conquer algorithmic paradigm. It was invented by Jhn von Neumann in
1945.

Analysis of the Merge sort:


1. Worest case performance O(n log n)
2. Best case performance O(n log n)
3. Average case performance O(n log n)
Advantages:

1. It has better cache performance

2. Merge Sort is a Stable sort

3. It is simpler to understand than heapsort

Limitation:

1. It need secondary storage device for the large amount of data.

2. It requires extra memeory space.

3. A small list will take fewer steps to sort than a large list.
Algorithm steps:
 If the list is of length 0 or 1, then it is already sorted. Otherwise:
 Divide the unsorted list into two sublists of about half the size.
 Sort each sublist recursively by re-applying merge sort.
 Merge the two sublists back into one sorted list.
C Program To Implement Merge Sort

CPP Program To Implement Merge Sort

C Program To Implement Merge Sort:

#include<stdio.h>
#include<conio.h>

void merge_split(int a[],int first,int last);


void merge(int a[],int f1,int l1,int f2,int l2);
int a[25],b[25];

void main()
{
int i,n;
clrscr();
printf("\n\nMERGE SORT");
printf("\n\n*********");
printf("\n\nEnter the limit : ");
scanf("%d",&n);
printf("\nEnter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
merge_split(a,0,n-1);
printf("\n\nSorted list : ");
for(i=0;i<n;i++)
printf("\n %d",a[i]);
getch();
}

void merge_split(int a[],int first,int last)


{
int mid;
if(first<last)
{
mid=(first+last)/2;
merge_split(a,first,mid);
merge_split(a,mid+1,last);
merge(a,first,mid,mid+1,last);
}
}

void merge(int a[],int f1,int l1,int f2,int l2)


{
int i,j,k=0;
i=f1;
j=f2;
while(i<=l1 && j<=l2)
{
if(a[i]<a[j])
b[k]=a[i++];
else
b[k]=a[j++];
k++;
}
while(i<=l1)
b[k++]=a[i++];
while(j<=l2)
b[k++]=a[j++];
i=f1;
j=0;
while(i<=l2 && j<k)
a[i++]=b[j++];
}

SAMPLE INPUT AND OUTPUT:

Enter the limit : 5


Enter the elements
5
4
3
2
1
Sorted list:
1
2
3
4
5

CPP Program To Implement Merge Sort:

#include<iostream.h>
#include<conio.h>
class MerSort
{
public:
int a[25],b[25],n;
void merge_split(int a[],int first,int last);
void merge(int a[],int f1,int l1,int f2,int l2);
};

void MerSort :: merge_split(int a[],int first,int last)


{
int mid;
if(first<last)
{
mid=(first+last)/2;
merge_split(a,first,mid);
merge_split(a,mid+1,last);
merge(a,first,mid,mid+1,last);
}
}
void MerSort :: merge(int a[],int f1,int l1,int f2,int l2)
{
int i,j,k=0;
i=f1;
j=f2;
while(i<=l1 && j<=l2)
{
if(a[i]<a[j])
b[k]=a[i++];
else
b[k]=a[j++];
k++;
}
while(i<=l1)
b[k++]=a[i++];
while(j<=l2)
b[k++]=a[j++];
i=f1;
j=0;
while(i<=l2 && j<k)
a[i++]=b[j++];
}
void main()
{
MerSort obj;
int i;
clrscr();
cout<<"\n\nMERGE SORT";
cout<<"\n\n*********";
cout<<"\n\nEnter the limit : ";
cin>>obj.n;
cout<<"\nEnter the elements\n";
for(i=0;i<obj.n;i++)
cin>>obj.a[i];
obj.merge_split(obj.a,0,obj.n-1);
cout<<"\n\nSorted list : ";
for(i=0;i<obj.n;i++)
cout<<obj.a[i]<<" ";
getch();
}

SAMPLE INPUT AND OUTPUT:

Enter the limit : 5


Enter the elements
5
4
3
2
1
Sorted list:
1
2
3
4
5

Implementation Of Quick Sort:


Sorting:
Sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used
orders are numerical order and lexicographical order.
Sorting algorithm classification:
Computaional complexcity.

Memory utilization

Stability-Maintaining relative order of records with equal keys.

No.of comparisions

Methods applied like insertion,exchange, selection,merging etc.


Sorting is a process of linear ordering of list of objects

Sorting techniques are categoried into:


1. Internal sorting

2. External sorting
Internal sorting:

It takes the place in the main memory of a computer.

Eg: Bubble sort,Insertion sort,Shell sort,Quick sort,Heap Sort,etc


External sorting:

It takes the place in secondary memory of a computer,Since the number of objects to be stored is
too large to fit in main memory.

Eg:Merge sort,Multiway Merge,Polyphase merge.


Quick Sort:
Qiuck sort is the most efficient internal sorting technique.It posseses a very good average case
behaviour among all the sorting techniques.It is also called partioning sort which uses divide and
conquer techniques.

Definition:
Pick an element from the array (the pivot), partition the remaining elements into those greater than
and less than this pivot, and recursively sort the partitions. There are many variants of the basic
scheme above: to select the pivot, to partition the array, to stop the recursion on small partitions,
etc.
 Quicksort is a comparison sort and, in efficient implementations, is not a stable sort.
 Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-
lists.
Analysis of the quick sort:
 Worest case performance O(n2)
 Best case performance O(n log n)
 Average case performance O(n log n)
Advantages of quick sort:
 It is faster than other O(N log N) algorims.
 It has better cache performance and high speed.
Limitation:

Requires More Memory space.


Algorithm steps:
 Pick an element, called a pivot, from the list.
 Reorder the list so that all elements which are less than the pivot come before the pivot and
so that all elements greater than the pivot come after it (equal values can go either way).
After this partitioning, the pivot is in its final position. This is called the partition operation.
 Recursively sort the sub-list of lesser elements and the sub-list of greater elements.
C Program To Implement Quick Sort

CPP Program To Implement Quick Sort

C Program To Implement Quick Sort:

#include<stdio.h>
#include<conio.h>
int i,j,n,pivot,a[20];
void quick(int a[],int left,int right);
void swap(int a[],int i,int j);
void main()
{
int n,a[20];
textcolor(15);
clrscr();
printf("\n\nQUICK SORT");
printf("\n\nEnter the limit : ");
scanf("%d",&n);
textcolor(4);
textcolor(5);
clrscr();
printf("\n\nEnter the element\n\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick(a,0,n-1);
textcolor(10);
printf("\n\nThe sorted list is \n\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
void quick(int a[],int first,int last)
{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i]<=pivot&&i<last)
i++;
while(a[j]>=pivot&&j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void swap(int a[],int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}

SAMPLE INPUT AND OUTPUT:

Enter the limit : 5


Enter the elements
5
4
3
2
1
The sorted list is
12345
CPP Program To Implement Quick Sort:

#include<iostream.h>
#include<conio.h>
class QuiSort
{
int i,j,pivot;
public:
int n,a[20];
void quick(int a[],int left,int right);
void swap(int a[],int i,int j);
};
void QuiSort :: quick(int a[],int first,int last)
{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i]<=pivot&&i<last)
i++;
while(a[j]>=pivot&&j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void QuiSort :: swap(int a[],int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void main()
{
QuiSort obj;
clrscr();
cout<<"\n\nQUICK SORT";
cout<<"\n\nEnter the limit : ";
cin>>obj.n;
clrscr();
cout<<"\n\nEnter the element\n\n";
for(int i=0;i<obj.n;i++)
cin>>obj.a[i];
obj.quick(obj.a,0,obj.n-1);
cout<<"\n\nThe sorted list is \n\n";
for(i=0;i<obj.n;i++)
cout<<obj.a[i]<<" ";
getch();
}

SAMPLE INPUT AND OUTPUT:

Enter the limit : 5


Enter the elements
5
4
3
2
1

The sorted list is


12345

Conversion Of Infix Expression To Postfix Expression:


Infix Expression:

Notation in which the operator separates its operands. Eg (a + b) * c. Infix notation requires the use
of brackets to specify the order of evaluation.

Postfix Expression:

Reverse Polish Notation or Suffix Notation in which the operator follows its operands. Eg a + b * c
represented as abc*+.

Algorithm steps:
1. Scan the Infix string from left to right.
2. Initialize an empty stack.
3. If the scanned character is an operand, add it to the Postfix string. If the scanned character is
an operator and if the stack is empty push the character to stack.
4. If the scanned character is an Operator and the stack is not empty, compare the precedence
of the character with the element on top of the stack (top Stack). If top Stack has higher
precedence over the scanned character pop the stack else push the scanned character to
stack. Repeat this step as long as stack is not empty and top Stack has precedence over the
character.
5. Repeat this step till all the characters are scanned.
6. After all characters are scanned, we have to add any character that the stack may have to the
Postfix string. If stack is not empty add top Stack to Postfix string and Pop the stack. Repeat
this step as long as stack is not empty.
C Program To Convert Infix Expression To Postfix Expression

C Program To Convert Infix Expression To Postfix


Expression:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
#define N 64
#define LP 10
#define RP 20
#define OPERATOR 30
#define OPERAND 40

// Left parentheses precedence. Minimum of all


#define LPP 0

// Addition Subtraction precedence. Minimum among all operator precedence


#define AP 1
#define SP AP

// Multiplication divisor precedence.


#define MP 2
#define DP MP

// Remainder precedence.
#define REMP 2

#define NONE 9

static char infix[N+1],stack[N],postfix[N+1];


static int top;

void infixtopostfix(void); /** POSTFIX CONVERSION FUNCTION **/


int gettype(char); /** TYPE OF EXPRESSION GENERATOR **/
void push(char); /** PUSH FUNCTION **/
char pop(void); /** POP FUNCTION **/
int getprec(char); /** PRECEDENCE CHECKER FUNCTION **/

void main()
{
char ch;
do
{
top=-1;
printf("\nEnter an infix expression\n");
fflush(stdin);
gets(infix);
infixtopostfix();
printf("\ninfix = %s\npost fix =%s\n",infix,postfix);
printf("\nDo you wish to continue\n");
ch=getche();
}while(ch=='Y' || ch=='y');
}

void infixtopostfix(void)
{
int i,p,l,type,prec;
char next;
i=p=0;
l=strlen(infix);
while(i<l)
{
type=gettype(infix[i]);
switch(type)
{
case LP:
push(infix[i]);
break;
case RP:
while((next=pop())!='(')
postfix[p++]=next;
break;
case OPERAND:
postfix[p++]=infix[i];
break;
case OPERATOR:
prec=getprec(infix[i]);
while(top>-1 && prec <= getprec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
}
i++;
}
while(top>-1)
postfix[p++]=pop();
postfix[p]='\0';
}

int gettype(char sym)


{
switch(sym)
{
case '(':
return(LP);
case ')':
return(RP);
case '+':
case '-':
case '*':
case '/':
case '%':
return(OPERATOR);
default :
return(OPERAND);
}
}

void push(char sym)


{
if(top>N)
{
printf("\nStack is full\n");
exit(0);
}
else
stack[++top]=sym;
}

char pop(void)
{
if(top<=-1)
{
printf("\nStack is empty\n");
exit(0);
}
else
return(stack[top--]);
}

int getprec(char sym)


{
switch(sym)
{
case '(':
return(LPP);
case '+':
return(AP);
case '-':
return(SP);
case '*':
return(MP);
case '/':
return(DP);
case '%':
return(REMP);
default :
return(NONE);
}
}

SAMPLE INPUT AND OUTPUT:

Enter any infix expression


3*6+4*2/5
Infix = 3*6+4*2/5
Post fix =36*42*5/+
Do you wish to continue
y
Enter an infix expression
Conversion Of Postfix Expression to Infix Expression:
Infix Expression:

Notation in which the operator separates its operands. Eg (a + b) * c. Infix notation requires the use
of brackets to specify the order of evaluation.

Postfix Expression:

Reverse Polish Notation or Suffix Notation in which the operator follows its operands. Eg a + b * c
represented as abc*+.

Algorithm steps:
1. Scan the Infix string from left to right.
2. Initialize an empty stack.
3. If the scanned character is an operand, add it to the Postfix string. If the scanned character is
an operator and if the stack is empty push the character to stack.
4. If the scanned character is an Operator and the stack is not empty, compare the precedence
of the character with the element on top of the stack (top Stack). If top Stack has higher
precedence over the scanned character pop the stack else push the scanned character to
stack. Repeat this step as long as stack is not empty and top Stack has precedence over the
character.
5. Repeat this step till all the characters are scanned.
6. After all characters are scanned, we have to add any character that the stack may have to the
Postfix string. If stack is not empty add top Stack to Postfix string and Pop the stack. Repeat
this step as long as stack is not empty.
C Program To Convert Postfix Expression To Infix Expression

C Program To Convert Postfix Expression To Infix


Expression:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define SIZE 30

typedef struct fix_tag


{
char s[SIZE][SIZE], dest[SIZE] ;
char t1[2], t2[2] ;
char ch1[SIZE], ch2[SIZE], ch3[SIZE] ;
int i, top ;
}postfix ;

/********** Function Declaration begins **********/


void initialization ( postfix * ) ;
void expression ( postfix *, char * ) ;
void push ( postfix *, char * ) ;
void pop ( postfix *, char * ) ;
void trans ( postfix * ) ;
void display ( postfix ) ;
/********** Function Declaration ends **********/

void main( )
{
postfix PF ;
char exp[SIZE] ;
clrscr( ) ;

initialization ( &PF ) ;

printf ( "\n\t\t Enter any Postfix expression :\n " ) ;


gets ( exp ) ;

expression ( &PF, exp ) ;


trans ( &PF ) ;

printf ( "\nThe resultant infix expression is: " ) ;


display ( PF ) ;

getch( ) ;
}

/********** Initialization of Strucutre variable **********/


/********** Function Definition begins **********/
void initialization ( postfix *p )
{
p -> i = 0 ;
p -> top = -1 ;
strcpy ( p -> dest, "") ;
}
/********** Function Definition ends **********/

/********** String Copy **********/


/********** Function Definition begins **********/
void expression ( postfix *p, char *c )
{
strcpy ( p -> dest, c ) ;
}
/********** Function Definition ends **********/

/********** Pushing expression **********/


/********** Function Definition begins **********/
void push ( postfix *p, char *str )
{
if ( p -> top == SIZE - 1 )
printf ( "\nStack Overflow." ) ;
else
{
p -> top++ ;
strcpy ( p -> s[p -> top], str ) ;
}
}
/********** Function Definition ends **********/

/********** Popping expression **********/


/********** Function Definition begins **********/
void pop ( postfix *p, char *a )
{
if ( p -> top == -1 )
printf ( "\nStack is empty." ) ;
else
{
strcpy ( a, p -> s[p -> top] ) ;
p -> top-- ;
}
}
/********** Function Definition ends **********/

/********** Postfix to Infix **********/


/********** Function Definition begins **********/
void trans ( postfix *p )
{
while ( p -> dest[p -> i] )
{

if( p -> dest[p -> i] == '' )


p -> i++ ;
if ( p -> dest[p -> i] == '%' || p -> dest[p -> i] == '*' ||
p -> dest[p -> i] == '-' || p -> dest[p -> i] == '+' ||
p -> dest[p -> i] == '/' || p -> dest[p -> i] == '$' )
{
pop ( p, p -> ch2 ) ;
pop ( p, p -> ch3 ) ;
p -> t1[0] = p -> dest[p -> i] ;
p -> t1[1] = '\0' ;
strcpy ( p -> ch1, p -> ch3 ) ;
strcat ( p -> ch1, p -> t1 ) ;
strcat ( p -> ch1, p -> ch2 ) ;
push ( p, p -> ch1 ) ;
}
else
{
p -> t1[0] = p -> dest[p -> i] ;
p -> t1[1] = '\0' ;
strcpy ( p -> t2, p -> t1 ) ;
push ( p, p -> t2 ) ;
}
p -> i++ ;
}
}
/********** Function Definition ends **********/
/********** Displaying expression **********/
/********** Function Definition begins **********/
void display ( postfix p )
{
char *t ;
t = p.s[0] ;
while ( *t )
{
printf ( "%c ", *t ) ;
t++ ;
}
}

SAMPLE INPUT AND OUTPUT:

Enter any Postfix expression:


12*3/4-
The resultant infix expression is: 1 * 2 / 3 – 4.

Implementation of Linked List Using Linked list Abstract


Data Type:
1. Set a node to contain INFO and LINK fields.

2. Allot memory dynamically for a node and declare it as a header H.

3. To create a linked lists get the element N and allot memory for a node SI

4. Set S1→ INFO = N; and S1→ LINK = NULL.

5. Repeat the above two steps for all the elements.

6. A node can be inserted at the front, in the middle or at the end of the list.

7. To insert a node X→ at the front check check whether the list is empty, if not set

8. X→LINK = H→LINK and H→LINK = X.

9. To insert a node X at the end travel till the end of the list and assign the last node‟s
LINK value to X

10. To insert a node X after the specified node Y, travel the list till the node Y is reached Set
X→LINK = Y→LINK = X

11. A node can be deleted at the front, in the middle or at the end of the list.
12. To delete a node X at the front set H→LINK = H→LINK→LINK.

13. To delete a node X at the end travel the list till the end and assign the previous at last node‟s
LINK value to be NULL.

14. To delete a node X after the specified node Y, Y→LINK = Y→LINK→LINK.

15. To search an element E traverse the list until E is found.

C Program To Implement Linked List Using Array Abstract Data Type:

C Program To Implement Linked List Using Array Abstract


Data Type:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>

void create( )
void insert( )
void delete( )
void display( )

struct node
{
int data;
struct node *link;
};
struct node *first = NULL, *last = NULL, *next, *prev, *cur;

void main( )
{
int ch;
clrscr( );
printf ("\n SINGLY LINKED LIST");
do
{
printf ("\n 1.CREATE \n 2.INSERT \n 3.DELETE \n 4.EXIT \n");
printf ("\n ENTER YOUR CHOICE: ");
scanf ("%d", &ch );
switch (ch)
{
case 1:
create( );
display( );
break;
case 2:
insert( );
display( );
break;
case 3:
delete( );
display( );
break;
case 4:
exit(0);
}
} while( ch <= 3)
}
void create( )
{
cur = ( struct node*)malloc (sizeof (struct node));
printf ("\n ENTER THE DATA: ");
scanf ("%d" , &cur?data);
cur?link = NULL;
first = cur;
last = cur;
}
void insert( )
{
int pos, c = 1;
cur = (struct node*)malloc(sizeof (struct node) );
printf (“\ENTER THE DATA :”);
scanf (“%d”, &cur?data);
printf(“\ENTER THE POSITION:”);
scanf (“%d”, &pos );
if ( (pos = = 1)&& (first! = NULL) )
{
cur?link = first;
first = cur;
}
else
{
next = first;
while (c < pos )
{
prev = next;
next = prev?link;
c++;
}
if ( prev = = NULL)
{
printf (“\n INVALID POSITION \n”);
}
else
{
cur?link = prev?link;
prev?link = cur;
if (cur?link = = NULL)
{
last = cur;
}
}
}
}

void delete( )
{
int pos, c=1;
printf (“\ENTER THE POSITION :”);
scanf (“%d”, &pos);
if (first = = NULL)
{
printf (“\n LIST IS EMPTY \n”);
}
else if (pos = = 1&& first?link = = NULL)
{
printf(“\Ndeleted element is %d\n”, cur?data);
free(cur);
}
else
{
next = first;
while (c < pos )
{
prev = next ;
next = next?link;
c++;
}
prev?link = next ?link;
next?link = NULL;
if (next = = NULL)
{
printf (“\n INVALID POSITION \n “);
}
else
{
printf (“\n DELETED ELEMENT IS%d\n”, next?data);
free (next);
if(prev?link = = NULL)
{
last = prev;
}
}
}
}

void display( )
{
cur = first;
while (cur! = NULL)
{
printf (“\n%d”, cur?data);
cur = cur?link;
}
}

SAMPLE INPUT AND OUTPUT:


1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 1
ENTER THE DATA: 10
1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 2
ENTER THE DATA: 20
ENTER THE POSITION: 1
20
10
1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 2
ENTER THE DATA: 30
ENTER THE POSITION: 2
20
30
10
1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 2
ENTER THE DATA: 40
ENTER THE POSITION: 4
20
30
10
40
1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 2
ENTER THE DATA: 50
ENTER THE POSITION: 6
20
30
10
40
1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 3
ENTER THE POSITION: 2
DELETED ELEMENT IS 30
20
10
40

1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 4

Implementation of Stack Using Array Abstract Data Type:


Algorithm Steps:
1. Declare an array S of Size N.
2. Assign TOP as a pointer to denote the top element in the stack.
3. Get the new element Y to be added in a stack.
4. If TOP is greater than or equal to N then display stack overflow; otherwise
 Set TOP = TOP + 1
 Set S[TOP] = Y.
 To delete top element from the stack check if TOP = 0, the display stack underflow,
otherwise
decrement TOP by one, and display S[TOP + 1]
 Display the stack S from 1 to TOP

C Program To Implement Stack Using Array Abstract Data Type:

#include<stdio.h>
#include<conio.h>
int i, top, item, s[10];
int max = 10;
void push ( int item, int s[ ] )
void pop (int s[ ] )
void display ( int s[ ] )
void display (int s[ ] )

void main( )
{
int ch;
clrscr( );
top = -1;
do
{
printf ( “\n\n 1.PUSH \n2.POP \n 3. EXIT \n” );
printf (“ \n ENTER UR CHOICE: “);
scanf ( “%d” , &ch );
switch (ch)
{
case 1:
printf ( “\tPUSH\n”);
if (top >= max – 1)
{
printf (“\n STACK IS FULL \n “);
}
else
{
printf (“\n ENTER AN ELEMENT :”);
scanf ("%d", &item);
push (item, s);
}
display(s);
break;
case 2:
printf ("\t\nPOP\n");
if (top < 0 )
{
printf ("\nSTACK IS EMPTY");
}
else
{
pop(s);
}
display(s);
break;
}}
while (ch!= 3)
getch( );
}
void push ( int item, int s[ ] )
{
top = top + 1;
s[top] = item;
}
void pop(int s[ ] )
{
item = s[top];
top = top – 1;
printf ("\n DELETED ELEMENT IS %d \n", item);
}
void display( int s[ ] )
{
printf ("\n");
for ( i = top; i >= 0; i-- )
{
printf ("\n %d", s[i]);
}
}
SAMPLE INPUT OUTPUT:

1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE: 1
PUSH
ENTER AN ELEMENT : 10
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE: 1
PUSH
ENTER AN ELEMENT: 20
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE: 2
POP
DELETED ELEMENT IS:20
10
1.PUSH
2.POP
3.EXIT
ENTER YOUR CHOICE: 3

Implementation of Stack Using Linked list Abstract Data


Type:
Algorithm Steps:
1. Create a linked list
2. To PUSH a node X travel the list until the end is reached. Assign last node‟s Link to X.
3. To POP a node X delete the last node and set the previous to last node‟s LINK to NULL.
4. To display the stack contents traverse the list from the header till the last node.

C Program To Implement Stack Using Linked list Abstract Data Type:


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
#include <stdlib.h>
struct node
{
int data;
struct node*link;
};
struct node*cur, *first;
void create( )
void push( )
void pop( )
void display( )
void create( )
{
printf(“\n ENTER THE FIRST ELEMENT :”);
cur = (struct node*)malloc(sizeof (struct node));
scanf (“%d”, &cur?data);
cur?link = NULL;
first = cur;
}
void display ( )
{
cur = first;
printf(“\n”);
while(cur!= NULL)
{
printf (“%d\n”, cur?data );
cur = cur ?link;
}
}
void push( )
{
printf (“\n ENTER THE NEXT ELEMENT: “);
cur = ( struct node*)malloc(sizeof (struct node));
scanf (“%d”, &cur?data);
cur?link = first;
first = cur;
}
void pop( )
{
if (first = = NULL)
{
printf(“\n STACK IS EMPTY \n”);
}
else
{
cur = first;
printf (“ \n DELETED ELEMENT IS %d \n”, first?data);
first = first?link;
free(cur);
}
}
void main( )
{
int ch;
clrscr( );
while(1)
{
printf (“\n\n1.CREATE \n2.PUSH\n 3.POP \n 4.EXIT \n”);
printf(“\n ENTER YOUR CHOICE”);
scanf (“%d”, &ch);
switch(ch)
{
case 1:
create( )
display( )
break;
case 2;
push( );
display( );
break;
case 3:
pop( );
display( );
break;
case 4:
exit (0);
}
}
}
SAMPLE INPUT OUTPUT:

1.CREATE
2.PUSH
3.POP
4.EXIT
ENTER YOUR CHOICE: 1
ENTER THE FIRST ELEMENT : 10
10
1.CREATE
2.PUSH
3.POP
4.EXIT
ENTER YOUR CHOICE: 2
ENTER THE FIRST ELEMENT : 20
20
10
1.CREATE
2.PUSH
3.POP
4.EXIT
ENTER YOUR CHOICE: 2
ENTER THE FIRST ELEMENT : 30
30
20
10
1.CREATE
2.PUSH
3.POP
4.EXIT
ENTER YOUR CHOICE: 3
DELETED ELEMENT IS 30
20
10
1.CREATE
2.PUSH
3.POP
4.EXIT
ENTER YOUR CHOICE: 4

Implementation of Queue Using Abstract Data Type:


Algorithm Steps:
1. Declare an array Q of size N.
2. Assign F and R to be the front and rear pointers of the queue and assign 0 to F and R.
3. Get the new element Y to be inserted into the queue.
4. If R is less than N, insert Y at the end, by incrementing R by 1. Otherwise display queue is
full.
5. If F is zero then assign F to be 1.
6. To delete an element check whether F is greater than zero, then delete an element pointed by
F, otherwise display queue is empty.
7. If F and R is equal the set F = R = 0; otherwise F = F + 1;
8. Display the queue Q from F to R.
C Program To Implement Queue Using Abstract Data Type:
#include <stdio.h>
#include <conio.h>
<p>int i, rear, front, item, s[10];
void insert ( int item, int s[ ]);
void del ( int s[ ]);
void display ( int s[ ]);
void main( )
{
int ch;
clrscr( );
front = 0;
rear = -1;
do
{
printf ( “\n\n1. Insertion \n2.Deletion \n3.Exit\n );
printf ( “\nEnter your choice: \n”);
{
case 1:
printf(“\n \t \t "Insertion \"\n\n");
if (rear >= 9)
{
printf ("\n\t\t"Queue is full\"\n");
}
else
{
printf ("Enter an element\n");
scanf("%d", &item );
insert (item, s)
}
display (s);
break;
case 2:
printf ("\n\t\t\"Deletion \"\n");
if ( front > rear)
{
printf ("\n \t\ "Queue is empty\"\n");
}
else
{
del(s);
}
display (s);
break;
}
}while (ch!=3 );
getch( );
}
void insert (int item, int s[ ] )
{
rear = rear + 1;
s[rear] = item;
}
void del ( int s[ ] )
{
item = s[front];
front = front +1;
printf ("\n \t \t \ "Deleted element is %d \"\n \n", item);
}
void display (int s[ ] )
{
printf (" \n ");
for ( i = front; i<= rear; i++)
{
printf ("\t %d", s[i]);
}
}
SAMPLE INPUT OUTPUT:
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 1
INSERTION
ENTER AN ELEMENT: 11
11
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 1
INSERTION
ENTER AN ELEMENT: 12
12
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 1
INSERTION
ENTER AN ELEMENT: 13
11 12 13

1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 2
DELETION
DELETED ELEMENT IS 11
13
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 2
DELETION

DELETED ELEMENT IS 12
13
1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 2
DELETION
QUEUE IS EMPTY

1.INSERTION
2.DELETION
3.EXIT
ENTER YOUR CHOICE: 3

Implementation of Binary Search Tree Using Abstract Data


Type:
Algorithm Steps:
1. Create the memory space for the root node and initialize the value to zero.
2. Read the value.
3. If the value is less than the root value, it is assigned as the left child of the root. Else if new
value is greater than the root value, it is assigned as the right child of the root. Else if there is
no value in the root, the new value is assigned as the root.
4. The step(2) and (3) is repeated to insert the „n‟ number of values.

Search Operation:
1. Read the value to be searched.
2. Check whether the root is not null
3. If the value to be searched is less than the root, consider the left sub-tree for searching the
particular element else if the value is greater than the root consider the right sub-tree to
search the particular element else if the value is equal then return the value that is the value
which was searched.
C Program To Implement Binary Search Tree Using Abstract Data Type

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}
*t, *temp;
int element;
void inorder (struct tree*);
struct tree *create (struct tree*, int);
struct tree *find (struct tree*, int);
struct tree *insert (struct tree*, int);
struct tree *del (struct tree*, int);
struct tree *findmin (struct tree*);
struct tree *findmax (struct tree*);
void main( )
{
int ch;
printf (“\n\n\t BINARY SEARCH TREE”);
do
{
printf (“\nMain Menu\n”);
printf (“\n1.Create \n2.Insert \n3.Delete \n4.Find \n5.Findmax \n6.Findmin”);
printf (“\n7.Exit”);
printf (“\nEnter your choice:”);
scanf (“%d”, &ch);
switch(ch)
{
case 1:
printf (“Enter the element\n”);
scanf (“%d”, &element);
t = create (t, element);
inorder(t);
break;
case 2:
printf (“Enter the element\n”);
scanf (“%d”, &element);
t = insert (t, element);
inorder(t);
break;
case 3:
printf (“Enter the data”);
scanf (“%d”, &element);
t = del (t, element);
inorder(t);
break;
case 4:
printf (“Enter the data”);
scanf (“%d”, &element);
temp = find (t, element);
if(temp?data = = element)
printf (“Element %d is found”, element);
else
printf (“Element is not found”);
break;
case 5:
temp = findmax(t);
printf(“Maximum element is %d”, temp?data);
break;
case 6:
temp = findmin(t);
printf (“Minimum element is %d”, temp?data);
break;
}
}
while(ch != 7)
}
struct tree *create (struct tree* t, int element)
{
t = (struct tree*) malloc (sizeof(struct tree));
t?(struct tree*)malloc(sizeof (struct tree) );
t?data = element;
t? lchild = NULL;
t? rchild = NULL;
return t;
}
struct tree *find (struct tree* t, int element)
{
if ( t= = NULL)
return NULL;
if (element< t?data)
return (find(t?rchild, element) );
else
return t;
}
struct tree *findmin (struct tree* t)
{
if ( t = = NULL)
return NULL;
else
if (t?lchild = = NULL)
return t;
else
return (findmin (t?lchild));
}
struct tree *findmax (struct tree* t)
{
if (t! = NULL)
{
while (t?rchild ! = NULL)
t = t?rchild;
}
return t;
}
struct tree *insert (struct tree* t, int element)
{
if (t= = NULL)
{
t = (struct tree*) malloc (sizeof(struct tree));
t?data = element;
t?lchild = NULL;
t?rchild = NULL;
return t;
}
else
{
if(element< t?data)
{
t?lchild = insert(t?lchild, element);
}
else
if (element> t?data)
{
t?rchild = insert (t?rchild, element);
}
else
if(element = = t?data)
{
printf ( “Element already present\n”);
}
return t;
}}
struct tree* del (struct tree* t, int element)
{
if (t = = NULL)
printf (“Element not found\n”);
else
if(element< t?data)
t?lchild = del (t?lchild, element);
else
if(element> t?data)
t?rchild = del (t?rchild, element);
else
if(t?lchild && t?rchild);
{
temp = findmin (t?rchild);
{
t?data = temp?data;
t?rchild = del (t?rchild, t?data);
}
else
{
temp = t;
if (t?lchild = = NULL)
t = t?rchild;
else
if (t?rchild = = NULL)
t = t?lchild;
free (temp);
}
return t;
}
void inorder (struct tree *t)
{
if (t = = NULL)
return;
else
{
inorder (t?lchild);
printf (“\t%d”, t?data);
inorder (t?rchild);
}
}
SAMPLE INPUT AND OUTPUT:

Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 1
Enter the element
12
12
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 2
Enter the element
13
12 13
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 3
Enter the data12
13
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 4
Enter the data13
Element 13 is found

Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 2
Enter the element
14
13 14
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 2
Enter the element
15
13 14 15

Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 5
Maximum element is 15

Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 6
Minimum element is 13

Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.Findmax
6.Findmin
7.Exit
Enter your choice: 7

Implementation Of Graph Traverses Using Depth First


Search:
Depth First Search :

Depth first works by selection one vertex V of G as a start vertex; V is marked visited. Then each
unvisited vertex adjacent to V is serached in trun using depth first serach recursively.This process
continues until a dead end (i.e)a vertex with no adjacent unvisited vertices is encountered.At a
deadend the algorithm backsup one edge to the vertex it came from and tries to continue visiting
unvisited vertices from there.

Advantages:

1.To check whether the undirected graph is connected or not.

2.To check whether the connected undirection graph is biconnected or not.]

3.To check the a Acyclicity of the directed graph.

Algorithm Steps:
Step 1: Choose any node in the graph . Designate it as the search node and mark it as vivited.

Step 2: Using the adjacency matrix of the graph, find a node adjacent to the search node that has not
been visited yet. Designate this as the new search node and mark it as visited.

Step 3: Repeat step 2 using t he new search node. If no nodes satisfying(2) can be found, return to
the previous search node and continue from there.

Step 4: When a return to the previous search in(3) is impossible,the serach from the originally
choosen search node is complete.

Step 5: If the graph still contains unvisited nodes,choose any node that has not been visited and
repeat step(1) through(4).
C Program To Implement Graph Traverses Using Depth First Search

CPP Program To Implement Graph Traverses Using Depth First Search

C Program To Implement Graph Traverses Using Depth First


Search:

#include<stdio.h>
#include<conio.h>
int a [10][10],visited[10].n;
void main()
{
int i,j;
void search from(int);
clrscr();
printf("enter the no. of nodes\n");
scanf("%d",&n);
printf("enter the adjacency matrix\n");
for(i=1;<=n;i++)
for(j=1;<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
visited[i]=0;
printf("Depth First Path:");
for(i=1;i<=n;i++)
if(visited[i]==0)
searchfrom(i);
}
void search from(int k)
{
int i;
printf("%d\t",k);
visited[k]=1;
for(i=1;i<=n;i++)
if(visited[i]==0)
searchfrom(i);
return;
}

SAMPLE INPUT AND OUTPUT:

Enter the no. of nodes


4
Enter the adjacency matrix
0101
0011
0001
0000
Depth First Path
1 2 3 4

CPP Program To Implement Graph Traverses Using Depth


First Search:

#include<iostream.h>
#include<conio.h>
int a [10][10],visited[10].n;
void main()
{
int i,j;
void search from(int);
clrscr();
cout<<"enter the no. of nodes\n";
cin>>n;
cout<<"enter the adjacency matrix\n";
for(i=1;<=n;i++)
for(j=1;<=n;j++)
cin>>a[i][j];
for(i=1;i<=n;i++)
visited[i]=0;
cout<<"Depth First Path:";
for(i=1;i<=n;i++)
if(visited[i]==0)
searchfrom(i);
}
void search from(int k)
{
int i;
printf("%d\t",k);
visited[k]=1;
for(i=1;i<=n;i++)
if(visited[i]==0)
searchfrom(i);
return;
}

SAMPLE INPUT AND OUTPUT:

Enter the no.of nodes


4
Enter the adjacency matrix
0101
0011
0001
0000
Depth First Path
1234

Implementation Of Binary Tree Traversing:


Binary tree traversing:

Definition:

It is a most common operation in binary tree. (i.e. pass through the tree). Enumerating each of its
nodes once. It is generally known as of visiting each node at once.
Three type of traversing orders:

1. Preorder traversing.

2. Inorder traversing.

3. Postoredr traversing.

Algorithm Steps:
Step1: Builds the binary tree.

Step 2: Determain the tree is non empty.


Step 3: Traversing type is preorder (depth-first order) then perform the following operations.

1. Visit the root.

2. Traverse the left subtree in preorder.

3. Traverse the right subtree in preorder.

Step 4: Traversing type is inorder (symmetric order) then performing the following operations.

1. Traverse the left subtree in inorder.

2. Visit the root.

3. Traverse the right subtree in inorder.

Step 5: Traversing type is postorder then performing the following operations.

1. Traverse the left subtree in postorder.

2. Traverse the right subtree in postorder.

3. Visit the root.

C Program To Implement Binary Tree Traversing


C Program To Implement Binary Tree Traversing:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
typedef struct tree*node;
node insert(int,node T);
void inorder(node T);
void preorder(node T);
void postorder(node T);
struct tree
{
int data;
struct tree*right,*left;
}*root;

void main()
{
nodeT= NULL;
int data,ch,i=0,n;
clrscr();
printf("\nEnter the number of elements in the Tree:");
scanf("%d",&n);
printf("\n The elements are :\n");
whil(i<n)
{
scanf("%d",&data):
T=insert(data,T);
i++;
}
printf("1. INORDER\t2.PREORDER\t3.POSTOTRDER\t4.EXIT");
do
{
printf("\nEnter your choide:");
scanf("%d",&ch);
switch (ch)
{
case1: printf ("Inorder traversal of the given Tree\n");
inorder(T);
break;
case2: printf("Preoroder traversal of the given Tree\n");
preorder(T);
break;
case3: printf("Postorder traversal of the given Tree\n");
posotorder(T);
break;
default:printf("Exit")
exit(0);
}

}
while(Ch<4);
getch();
node insert(intX, node T)
{
struct tree*newnode;
newnode=malloc(sizeof(struct tree));
if(newnode==NULL)
printf("Out of space\n");
else
{
if(T==NULL)
{
newnode->data=X;
newnode->left=NULL;
newnode->right=NULL;
T=newnode;
}
else
{
if(X<T->data)
T->left=insert(X,T->left);
else
T->right=insert(X,T->right);
}
}
return T;
}
void inorder(node T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d\t",T->ddata);
inorder(T->right);
}
}
void preorder(node T)
{
if(T!=NULL)
{
printf("%d\t",T->data);
preorder(T->left);
preorder(T->right);
}
}
void postoroder(node T)
{
if(T!=NULL);
{
postorder(T->left);
postorder(T->right);
printf("%d\t",T->data);
}
}

SAMPLE INPUT AND OUTPUT:

Enter the number of elements in the Tree:4


The elements are:
30
20
40
25
1. IN ORDER
2. PREORDER
3. POSTORDER.
4. EXIT
Enter your choice: 1
Inorder traversal of the given Tree
20 25 30 40
Preorder traversal of the given Tree
30 20 25 40
Postorder traversal of the given Tree
25 20 40 30
Enter your choice: 4

You might also like