Data Structure Program Using C and CPP
Data Structure Program Using C and CPP
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).
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;
}
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);
}
}
}
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();
}
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.
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:
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:
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
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();
}
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:
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:
#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);
}
}
}
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);
}
}
}
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
}
}
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;
}
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.
4. Assign first=last=cur.
4. Availability of the position is true then assing cur's link as first and first=cur.
3. If position is first.
4. If position is last.
#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
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::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..";
}
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 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;
}
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:
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
struct linkedlist
{
int item;
struct linkedlist *right,*left;
};
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);
}
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
#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);
}
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.
3. Circularly doubly linked list allows traversing the list in either direction.
Algorithm Steps:
#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);
}
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
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
}
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
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
step 2: Read the cofficient and power of the polynomial quation two and assign it's elements into a
linked list.
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.
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.
void main()
{
void create(void);
void display(void);
void polyaddtion(void);
void sorting(void);
clrscr();
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;
}
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;
/*-----------------------------------------------------------------------------*/
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;
}
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;
}
node=(bar *)malloc (sizeof(bar));
ptr->link=node; //update ptr list C
}//end of while
/*------------------------------------------------------------------------------------*/
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();
getch();
}
SAMPLE INPUT AND OUTPUT:
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 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.
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();
}
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class BinarySearch
{
int a[25],n;
public:
void getdata();
void sorting();
void binarysearch();
};
}
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();
}
Sorted list
1
2
3
4
5
Infix Expression :
Any expression in the standard form like "2*3-4/5" is an Infix( Inorder) expression.
Postfix Expression :
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
struct postfix
{
int stack[MAX];
int top,nn;
char *s;
};
________________________________
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
#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);
};
________________________________
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
Memory utilization
No.of comparisions
2. External sorting
Internal sorting:
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:
Advantages:
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 )
3) list [count]=list[inner_count]
4) a[inner_count]=temp
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:
#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<<"*************************";
}
Memory utilization
No.of comparisions
2. External sorting
Internal sorting:
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:
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
#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();
}
#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];
}
Memory utilization
No.of comparisions
2. External sorting
Internal 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
Insertion sorts works by taking elements from the list one by one and inserting them in their current
position into a new sorted list.
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]
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:
#include <iostream.h>
#include <conio.h>
class InsertionSort
{
public:
void insertion_sort(int [],int);
};
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:
5
4
3
2
1
SORTED LIST
1
2
3
4
5
Memory utilization
No.of comparisions
2. External sorting
Internal 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.
The whole array is first fragmented into K segments, where K is preferably a prime number.
Step 2:
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:
The insertion sort is applied in each segment, so each successive segment is partially sorted.
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();
}
Sorted list:
1
2
3
4
5
Sorted list:
1
2
3
4
5
No.of comparisions
2. External sorting
Internal 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.
2.It has the advantages of worst case O(N log N) running time.
Limitations:
The array elements aer stored using deletemin operation,which gives the elements arranged in
descending order.
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
#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;
}
Enter No Of Elements:5
Enter Elements To Be Sorted
5
4
3
2
1
Sorted Element
1
2
3
4
5
Memory utilization
No.of comparisions
2. External sorting
Internal 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.
i) Dividing Phase.
Limitation:
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
#include<stdio.h>
#include<conio.h>
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();
}
#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);
};
Memory utilization
No.of comparisions
2. External sorting
Internal 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.
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:
#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;
}
#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();
}
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
#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
// Remainder precedence.
#define REMP 2
#define NONE 9
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';
}
char pop(void)
{
if(top<=-1)
{
printf("\nStack is empty\n");
exit(0);
}
else
return(stack[top--]);
}
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
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define SIZE 30
void main( )
{
postfix PF ;
char exp[SIZE] ;
clrscr( ) ;
initialization ( &PF ) ;
getch( ) ;
}
3. To create a linked lists get the element N and allot memory for a node SI
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
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.
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;
}
}
1. CREATE
2. INSERT
3. DELETE
4. EXIT
ENTER YOUR CHOICE: 4
#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
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
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
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
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:
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
#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;
}
#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;
}
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 4: Traversing type is inorder (symmetric order) then performing the following operations.
#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);
}
}