0% found this document useful (0 votes)
12 views

DS Practicals SE

Uploaded by

Mr R K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

DS Practicals SE

Uploaded by

Mr R K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

!!Sab Ka Malik Atma!!

Vishwatmak Jangli Maharaj Ashram Trust Atma


Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Data Structures Laboratory –

CSL303 After completion of this Laboratory course, the learner will

be able to:Lab Outcomes:

LO1: Implement various linear and nonlinear data structures.


LO2: Handle operations like insertion, deletion, searching and traversing on various data
structures.
LO3: Design applications of various data structures.

List of
Experiments
Subject:- Data Structures Laboratory – CSL303 Class: SE SEM: III

Sr. No. Title of Experiments LO addressed

1 Implement stack using array. LO1

2 Implement continuity of different types of parenthesis using stack. LO3

3 Implement conversion of Infix to Postfix. LO3

4 Implement a queue using an array. LO1

5 Implement a circular queue using arrays. LO1

6 Implement singly linked list. LO1

7 Implement stack using linked list. LO1

8 Implement Binary Search Tree. LO1

9 Implement Bubble Sort. LO2

10 Implement Quick Sort. LO2

11 Implement Binary Search. LO2

12 Implement Depth First Search and Breadth First Search. LO2

Subject In-Charges:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust Atma
Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 1

Aim: Write a program to implement stack using an array.

Theory:
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). Stack is an
abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows
adding and removing elements in a particular order. Every time an element is added, it goes on
the top of the stack and the only element that can be removed is the element that is at the top of
the stack, just like a pile of objects.

Basic features of Stack:


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
3. push() function is used to insert new elements into the Stack and pop() function is used to
remove an element from the stack. Both insertion and removal are allowed at only one
end of Stack called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be in
Underflow state if it is completely empty.
Algorithm:

Algorithm for PUSH operation


1. Check if the stack is full or not. If the stack is full, then print error of overflow and
exitthe program by going to step 4..
2. If the stack is not full,
then Do Top = Top +
1
3. Set Stack [Top] = VALUE.
4. End

Algorithm for POP operation


1. Check if the stack is empty or not. If the stack is empty, then print error of underflow
and exit the program by going to step 4.
2. If the stack is not empty, then Print VALUE = STACK [Top]
3. Do Top = Top - 1
4. End
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Program:

#include<stdio.h> void push()

#include<conio.h {

>#define MAX 50 int x;

int stack[MAX], top=- if (top >= MAX - 1)

1;void push(); {

void pop(); printf("STACK is over flow\n");

void peek();

void }

display();int else

main() {

{ printf("Enter a value to be pushed:");

int choice; scanf("%d", &x);

clrscr(); top++;

printf("\n\t ###MENU###"); stack[top] = x;

printf("\n\t1.PUSH\n\t2.POP\n\t }

3.DISPLAY\n\t4.PEEK \n\t5.EXIT\n"); }

do void pop()

{ {

printf("Enter the Choice:"); if (top <= -1)

scanf("%d", &choice); {

switch (choice) printf("Stack is under flow.\n");

{ }

case 1: else

{
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

push() {

; printf("The popped elements is %d.\n",


stack[top]);
break;
top--;
}
}
case 2:
}
{
void peek()
pop();
{
break;
if (top == -1)
}
printf("Nothing to Peek.\n");
case 3:
else
{
printf("Top Element is : %d.\n",
display(); stack[top]);

break; }

} void display()

case 4: {

{ int i;

peek(); if (top >= 0)

break; {

} printf("The elements in STACK

case 5: \n");for (i = top; i >= 0; i--)

{ printf("%d\n", stack[i]);

printf("Exit }

Point");break; else

} {

default: printf("The STACK is empty.\n");

{ }

printf("Invalid Input !");


!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

} }

} while (choice !=

5);getch();

return 0;

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 2

Aim: Write a program to implement conversion of Infix to Postfix.

Theory:

Expression conversion is the most important application of stack. Given an infix expression, it
can be converted to both prefix and postfix expression. Postfix notation is said to be harder to
learn.

Infix expression:The expression of the form a op b. When an operator is in-between every pair
of operands.

Postfix expression:The expression of the form a b op. When an operator is followed for every
pair of operands.

Algorithm:

1. Scan the infix expression from left to right.


2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the
operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.
…..3.2 Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. After doing that Push the scanned operator tothe
stack. (If you encounter parenthesis while popping then stop there and push the scanned
operator in the stack.)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Program:

#include<stdio.h> printf("\nInvalid infix Expression.\n");

#include<conio.h> }

#include<stdlib.h> /* for exit() */ }

#include<ctype.h> /* for isdigit(char ) */ int precedence(char symbol)

#include<string.h> {

#define SIZE if(symbol == '^')/* exponent operator,


highest precedence*/
100 char
{
stack[SIZE]; int
return(3);
top = -1;
}
void push(char item)
else if(symbol == '*' || symbol == '/')
{
{
if(top >= SIZE-1)
return(2);
{
}
printf("\nStack Overflow.");
else if(symbol == '+' || symbol == '-')
} /* lowest precedence */

else {
{ return(1);
top = top+1; }
stack[top] = item; else
} {
}char pop() return(0);
{ }
char item ;
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

if(top <0) } void InfixToPostfix(char infix_exp[],


charpostfix_exp[])
{
{
printf("stack under flow: invalid
infix expression"); int i, j;

//getchar(); char item;

exit(1); char x;

else push('('); /* push '(' onto


stack */
{
strcat(infix_exp,")"); /*
item = stack[top]; add ')' to infix expression */

top = top-1;

} i=0

return(item); ;

}int is_operator(char symbol) j=0

{ ;

if(symbol == '^' || symbol == '*' || item=infix_exp[i]; /* initialize


symbol == '/' || symbol == '+' || symbol =='-') before loop*/

return 1; while(item != '\0') /* run loop till end of


infix expression */
}
{
else
if(item == '(')
{
{
return 0;
push(item);

else if( isdigit(item) ||


isalpha(item))
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

postfix_exp[j] =
else if(is_operator(item) == 1) item; /* add operand symbol to
/* means symbol is operator */ postfix expr */

{ j++;
x=pop()
;while(is_operator(x) == 1 }
&&
illegeal symbol */
precedence(x)>= precedence(item))

{
}
postfix_exp[j] = x; /* so pop all if(top>0)
higher precendence operator and */
{
j++;
printf("\nInvalid infix
x = pop(); Expression.\n"); /* the it is illegeal
/* add them to postfix expresion */ symbol */
}

else if(item == ')') /* if current }


symbol is ')' then */

x = pop(); /* pop
and keep popping until */ postfix_exp[j] = '\0';
while(x != '(') /* '(' }
encounterd */

{
int main()
postfix_exp[j] =
{
x;j++;
clrscr();
x = pop();
char infix[SIZE], postfix[SIZE];
} /* declare infix string and postfix string */
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

printf("\nEnter Infix expression : ");

gets(infix);

InfixToPostfix(infix,postfix);
/* call to convert */

printf("Postfix Expression: ");

puts(postfix); /* print postfix


expression */

getch();

return 0;

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 3

Aim: Write a program to evaluate Postfix expression using stack ADT.

Theory: Postfix evaluation is an important concept in computer science that allows us to perform
arithmetic operations on postfix expressions. In this article, we will discuss postfix evaluation in the
context of C programming language.

Postfix evaluation algorithm is a simple algorithm that allows us to evaluate postfix expressions. The
algorithm uses a stack to keep track of operands and performs arithmetic operations when an operator
is encountered.

Algorithm:
The algorithm can be summarized in the following steps:

1. First of all, it will Create an empty stack.

2. After that, it Scan the expression from left to right.

3. If an operand is encountered, it push it onto the stack.

4. If an operator is encountered, pop the top two operands from the stack, perform the operation,
and push the result back onto the stack.

5. After that, it Continue scanning the expression until all tokens have been processed.

6. When the expression has been fully scanned, the result will be the top element of the stack.

Program:

#include <stdio.h> }
#include <stdlib.h> int pop() {
#define MAX_SIZE 100 if (top < 0) {
// Stack implementation printf("Stack Underflow\n");
int stack[MAX_SIZE]; return -1;
int top = -1; }
void push(int item) { int item = stack[top];
if (top >= MAX_SIZE - 1) { top--;
printf("Stack Overflow\n"); return item;
return; }
} int is_operator(char symbol) {
top++; if (symbol == '+' || symbol == '-' ||
stack[top] = item; symbol == '*' || symbol == '/') {
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

return 1;
}
return 0; }
} push(result);
int evaluate(char* expression) { }
int i = 0; i++;
char symbol = expression[i]; symbol = expression[i];
int operand1, operand2, result; }
result = pop();
while (symbol != '\0') { return result;
if (symbol >= '0' && symbol <= }
'9') {
int num = symbol - '0'; int main() {
push(num); char expression[] = "5 6 7 + * 8 -";
} int result = evaluate(expression);
else if (is_operator(symbol)) { printf("Result= %d\n", result);
operand2 = pop(); return 0;
operand1 = pop(); }
switch(symbol) {
case '+': result = operand1 +
operand2; break;
case '-': result = operand1 -
operand2; break;
case '*': result = operand1 *
operand2; break;
case '/': result = operand1 /
operand2; break;

Outcome:

Result= 57
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 4

Aim: Write a program to Implement queue using array.

Theory:

A queue is an abstract data structure that contains a collection of elements. Queue implementsthe
FIFO mechanism i.e. the element that is inserted first is also deleted first. In other words, the
least recently added element is removed first in a queue.

In this, the function Insert() inserts an element into the queue. If the rear is equal to n-1, then the
queue is full and overflow is displayed. If front is -1, it is incremented by 1. Then rear is
incremented by 1 and the element is inserted in index of rear.

In the function Delete(), if there are no elements in the queue then it is underflow condition.
Otherwise the element at front is displayed and front is incremented by one.

In the function display(), if front is -1 then queue is empty. Otherwise all the queue elements
are displayed using a for loop.

Algorithm:

Algorithm to insert element in Queue:

1. If (REAR == Max - 1) Then [Check for

overflow] Print: Overflow , Go to Step 4. End of

If.

2. If (FRONT and REAR ==

-1) Set FRONT = REAR = 0

Else Set REAR = REAR + 1 [Increment REAR

by 1][End of If]

3. Set QUEUE[REAR] = VALUE

4. Exit
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Algorithm to delete element from Queue:


1. If FRONT == -1 then
Print “Queue Underflow”, Go to step 4.
End of if
2. Value = QUEUE[FRONT]
3. If
FRONT=REA
RThen
Set FRONT=REAR=-1
Else
Set FRONT= FRONT+ 1
4. Exit

Program:

# include<stdio.h> void display()


#include<conio.h> {
# define MAX 5 int i;
if(front == -1)
int queue[MAX]; {
int front = -1; printf("Queue is empty\n");
int rear = -1; return;
void insert(int i) }
{ printf("Queue elements :\n");
if((front == 0 && rear == MAX-1) || (front
== rear+1)) for(i=front;i<=rear;i++)
{ {
printf("Queue Overflow \n"); printf("\t %d ",queue[i]);
return; }
} }
if (front == -1) int main()
{ {
front = 0; int choice,i;
rear = 0; clrscr();
} do
else {
{ printf("1.Insert\n");
if(rear == MAX-1) printf("2.Delete\n");
rear = 0; printf("3.Display\n");
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

else printf("4.Quit\n");
rear = rear+1;
} printf("Enter your choice : ");
queue[rear] = i ; scanf("%d",&choice);
}
void del() switch(choice)
{ {
if (front == -1) case 1 :
{ printf("Input the
printf("Queue Underflow\n"); element for insertion in queue : ");
return ; scanf("%d", &i);
}
printf("Element deleted from queue is : insert(i);
%d\n",queue[front]); break;
if(front == rear) case 2 :
{ del();
front = -1; break;
rear=-1; case 3:
} display();
else break;
{ case 4:
if(front == MAX-1) break;
front = 0; default:
else printf("Wrong
front = front+1; choice\n");
} }
} }while(choice!=4);

return 0;
}
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 5

Aim: Write a program to Implement circular queue using array.

Theory:

Circular Queue is a linear data structure in which the operations are performed based on FIFO
(First In First Out) principle and the last position is connected back to the first position to make
a circle. It is also called ‘Ring Buffer’.

Operations on Circular Queue:

● Front: Get the front item from queue.


● Rear: Get the last item from queue.
● enQueue(value) This function is used to insert an element into the circular queue.
In a circular queue, the new element is always inserted at Rear position.
1. Steps:Check whether queue is Full – Check ((rear == MAX-1 && front
== 0) || (rear == front-1)).
2. If it is full then display Queue is full. If queue is not full then, check
if (rear == MAX – 1 && front != 0) if it is true then set rear=0 and
insertelement.
● deQueue() This function is used to delete an element from the circular queue. In a
circular queue, the element is always deleted from front position.
1. Steps:Check whether queue is Empty means check (front==-1).

2. If it is empty then display Queue is empty. If queue is not empty then


step 3
3. Check if (front==rear) if it is true then set front=rear= -1 else check
if (front==MAX-1), if it is true then set front=0 and return the
element.
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Program:

# while(x <= MAX-1)


include<stdio.h> {
#include<conio.h printf("%d ",queue[x]);
> # define MAX 5 x++;
}
int queue[MAX]; x = 0;
int front = -1; while(x <= y)
int rear = -1; {
void insert(int i) printf("%d ",queue[x]);
{ x++;
if((front == 0 && rear == MAX-1) || }
(front == rear+1)) }
{ printf("\n");
printf("Queue Overflow \n"); }
return;
} int main()
if (front == -1) {
{ int choice,i;
front = 0; clrscr();
rear = 0;
} do
else {
{ printf("1.Insert\n");
if(rear == MAX-1 && front!=0) printf("2.Delete\n");
rear = 0; printf("3.Display\n");
else printf("4.Quit\n");
rear = rear+1;
} printf("Enter your choice : ");
queue[rear] = i ; scanf("%d",&choice);
}
void del() switch(choice)
{ {
if (front == -1) case 1 :
{ printf("Input
printf("Queue Underflow\n"); the element for insertion in queue : ");
return ; scanf("%d", &i);
}
printf("Element deleted from queue is
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

: %d\n",queue[front]); insert(i);
if(front == rear) break;
{ case 2 :
front = -1; del();
rear=-1; break;
} case 3:
else display()
{ ; break;
if(front == MAX-1) case 4:
front = 0;
break;
else
default:
front = front+1;
printf("Wrong
}
choice\n");
}
}
void display()
}while(choice!=4);
{
int x = front,y =
return 0;
rear;if(front == -1)
}
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( x<= y )
while(x <= y)
{
printf("%d
",queue[x]);x++;
}
else
{
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 6

Aim: Write a program to Implement singly linked list.

Theory:
A linked list is a linear collection of data elements. These data elements are called nodes. Linked list is a
data structure which in turn can be used to implement other data structures. Thus, it acts as a building
block to implement data structures such as stacks, queues, and their variations. A linked list can be
perceived as a train or a sequence of nodes in which each node contains one or more data fields and a
pointer to the next node.

Algorithms:

To insert a new node at the beginning To insert a new node at the end
Step 1: IF AVAIL = NULL Step 1: IF AVAIL = NULL
Write Write
OVERFLOWGo
OVERFLOWGo
to Step 1
to Step 7 [END [END OF IF]
OF IF] Step 2: SET = AVAIL Step
Step 2: SET NEW_NODE = 3: SET AVAIL = AVAIL
AVAILStep 3: SET AVAIL = NEXTStep 4: SET DATA
AVAIL NEXT Step 4: SET = VAL
DATA = VAL Step 5: SET NEW_NODE =
NULLStep 6: SET PTR = START
Step 5: SET NEW_NODE NEXT =
Step 7: Repeat Step 8 while PTR NEXT !=
STARTStep 6: SET START = NULLStep 8: SET PTR = PTR NEXT
NEW_NODE [END OF LOOP]
Step 7: EXIT Step 9: SET PTR
NEXT =Step 10: EXIT
To insert a new node after a node that has value To insert a new node before a node that has
NUM value NUM
Step 1: IF AVAIL = NULL Step 1: IF AVAIL = NULL
Write Write
OVERFLOWGo OVERFLOWGo
to Step 12 [END to Step 12 [END
OF IF] OF IF]
Step 2: SET = AVAIL Step 2: SET = AVAIL
Step 3: SET AVAIL = AVAIL Step 3: SET AVAIL = AVAIL NEXT
NEXTStep 4: SET DATA = Step 4: SET NEW_NODE->DATA =
VAL VALStep 5: SET PTR = START
Step 5: SET PTR = Step 6: SET PREPTR = PTR
START Step 6: SET Step 7: Repeat Steps 8 and 9 while PTR DATA !=
PREPTR = PTR NUM
Step 7: Repeat Steps 8 and 9 while PTR NEXT !=
NUM
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Step 8: SET PREPTR = Step 8: SET PREPTR =


PTR Step 9: SET PTR = PTR Step 9: SET PTR =
PTR NEXT[END OF PTR NEXT[END OF
LOOP] LOOP]
Step 10: PREPRT- Step 1 : PREPTR NEXT
>NEXT=NEW_NODE Step 11: SET =NEW_NODE Step 11: SET
NEW_NODE NEXT = PTR Step 12: NEW_NODE NEXT = PTRStep 12:
EXIT EXIT
To delete the firstnode To delete the last node
Step 1: IF START = Step 1: IF START =
NULL Write NULL Write
UNDERFLOW UNDERFLOW
Go to Step 5 Go to Step 8
[END OF [END OF
IF] IF]
Step 2: SET PTR = START Step 2: SET PTR = START
Step 3: SET START = START Step 3: Repeat Steps 4 and 5 while PTR NEXT !=
NEXTStep 4: FREE PTR NULL
Step 5: EXIT Step 4: SET PREPTR =
PTR Step 5: SET PTR =
PTR NEXT[END OF
LOOP]
Step 6: SET PREPTR NEXT =
NULLStep 7: FREE PTR
Step 8: EXIT
To delete the node after a given node To delete the node before a given node
Step 1: IF START = Step 1: IF START =
NULLWrite NULLWrite
UNDERFLOW UNDERFLOW
Go to Step 10 Go to Step 10
[END OF IF] [END OF IF]
Step 2: SET PTR = Step 2: SET PTR =
START Step 3: SET START Step 3: SET
PREPTR = PTR PREPTR = PTR
Step 4: Repeat Steps 5 and 6 while PREPTR DATA Step 4: Repeat Steps 5 and 6 while PTR->DATA !=
!= NUM NUM
Step 5: SET PREPTR = Step 5: SET PP= PREPTR
PTR Step 6: SET PTR = Step 6: SET PREPTR =
PTR NEXT[END OF PTR Step 7: SET PTR =
LOOP] PTR NEXT[END OF
Step 7: SET TEMP = PTR LOOP]
Step 8: SET PREPTR NEXT = PTR Step 8: SET PP->NEXT =
NEXTStep 9: FREE TEMP PTRStep 9: FREE
Step 10 : EXIT PREPTR
Step 10 : EXIT
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301
To sort the list
Step 1: IF START =
NULLWrite
UNDERFLOW
Go to Step 1
[END OF
IF]
STEP 2: SET ptr1=START
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

STEP 3: SET ptr2= ptr1 ->


nextSTEP 4: while(ptr1 ->
next != NULL) do
SET ptr2 = ptr1 ->
next;while(ptr2 !=
NULL)
do
if(ptr1 -> data > ptr2 -> data)
do
SET temp = ptr1 -> data;
SET ptr1 -> data = ptr2 -> data;
SET ptr2 -> data = temp;
End of IF
SET ptr2 = ptr2 -> next;
End of while
ptr1 = ptr1 -> next;
End of while
STEP 5: End

Program:

#include<stdio.h> void Delete()


#include<conio.h> {
#include<stdlib.h> int n,found=0;
struct Node q=start;
{int info; if (q==NULL)
struct Node *next; printf ("\nlinked list is empty");
}*start ,*p,*q,*r; else
void create(); {printf("\nenter number to be deleted");
void Delete(); scanf("%d",&n);
void display(); while((found==0)&&(q!=NULL))
void main() {if (q->info==n)
{ found=1;
int ch; else
clrscr(); q=q->next;
start=NULL; }
if (found ==0)
printf("\n\n1.create\n2.delete\n3.display\n4.exit printf("\nno such element in linked list");
"); else
while(1) {if (q==start)
{ {start=start->next;
printf("\n enter your choice"); q->next=NULL;
scanf ("%d",&ch); free(q);
switch (ch) }
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

{ else
case 1:create();break; {r=start;
case 2:Delete();break; while(q->next!=q)
case 3:display();break; {r=r->next;
case 4:exit(0); break; r->next=q-
default : printf("wrong choice"); >next;q-
} >next=NULL;
}} free(q);
void create() }}}}}
{p=malloc(sizeof(struct void display()
Node));printf("\nenter data"); {
scanf("%d",&p->info); if (start==NULL)
p- printf ("\nlinked list is empty");
>next=NULL; else
if(start==NUL {
L)start=p; q=start;
else while (q!=NULL)
{q=start; {printf("\t %d",q-
while(q->next!=NULL) >info);q=q->next;
{q=q- }}}
>next;}q-
>next= p;
}
}

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 7

Aim: Write a program to implement stack using linked list.

Theory:
If the array size cannot be determined in advance, then the other alternative, i.e., linked representation, is
used. The storage requirement of linked representation of the stack with n elements is O(n), and the
typical time requirement for the operations is O(1). In a linked stack, every node has two parts—one that
stores data and another that stores the address of the next node. The START pointer of the linked list is
used as TOP. All insertions and deletions are done at the node pointed by TOP. If TOP = NULL, then it
indicates that the stack is empty.

Algorithm:

To insert an element in a linked stack To delete an element from a linked stack


Step 1: Allocate memory for the new node and Step 1: IF TOP =
name it as NEW_NODE NULLPRINT
Step 2: SET NEW_NODE DATA = UNDERFLOW
VALStep 3: IF TOP = NULL [END OF IF]
SET NEW_NODE NEXT = Step 2: SET PTR = TOP
NULLSET TOP Step 3: SET TOP = TOP ->
=NEW_NODE NEXTStep 4: FREE PTR
ELSE Step 5: END
SET NEW_NODE NEXT =
TOPSET TOP =
NEW_NODE
[END OF IF]
Step 4: END

Program:

#include<stdio.h> void push()


#include<conio.h> {
#include<stdlib.h>struct p=malloc(sizeof(struct Node));
Node{ printf("\nEnter data"); scanf("%d",&p-
int info; >info); if(top==NULL)
struct Node*next; {
}*top,*p,*q;void top=p;
push();void }
pop(); void else{
Display(); void p->next=top;
main() top=p;
{
int ch;
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

clrscr(); }
top=NULL; }
void pop()
printf("\n\n1.PUSH\n2.POP\n3.DISPLA {
Y\n4.EXIT"); q=top;
while(1) if(q==NULL)
{ printf("\nStack is empty");else{
printf("\nEnter yourchoice"); printf("Element
scanf("%d",&ch); popped=%d",top->info);
switch(ch) top=top->next;q-
{ >next=NULL;
case 1: push();break; free(q);
case 2:pop();break; }
case 3:Display();break; }
case 4:exit(1); void Display()
default:printf("\nWrong {
choice"); q=top;
} if(q==NULL)
} printf("\nStack is empty");Else{
getch(); printf(“\n Stack elementsare: \t”);
} while(q!=NULL)
{
printf("\t%d",q->info);q=q->next;
}}}

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 8

Aim: Write a program to implement Binary Search Tree.

Theory:
A binary search tree, also known as an ordered binary tree, is a variant of binary tree in which the nodes
are arranged in an order. In a binary search tree, all the nodes in the left sub-tree have a value less than
that of the root node. Correspondingly, all the nodes in the right sub-tree have a value either equal to or
greater than the root node.

Algorithms:

to insert a given value in a binary search tree to search for a given value in a binary
searchtree
InsertElement(TREE,VAL)
Step 1: Allocate memory for new variable ptr SearchElement (TREE, VAL)
SET ptr–>data = val Step 1: IF TREE DATA = VAL OR TREE =
SET ptr–>left = NULL
NULL SET ptr– Return
>right = NULLStep TREEELSE
2: IF VAL < TREE DATA
IF Return searchElement(TREE LEFT,
TREE=NUL VAL)ELSE
LSET Return searchElement(TREE RIGHT,
TREE=ptr VAL)[END OF IF]
else [END OF IF]
SET parentptr=NULL Step 2: END
SET nodeptr=TREE
While to delete a binary search tree
nodeptr!=NULLdo
SET parentptr=nodeptr deleteTree(TREE)
IF val<nodeptr–>data Step 1: IF TREE != NULL
SET nodeptr=nodeptr–>left deleteTree (TREE
else LEFT) deleteTree
SET nodeptr = nodeptr–>right (TREE RIGHT)Free
END OF IF (TREE)
IF val<parentptr–>data [END OF IF]
SET parentptr–>left = ptr; Step 2: END
else
SET parentptr–>right = ptr;
END OF IF
END OF
WHILEEND
OF IF
Step 3: END
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

to delete a node from a binary search tree pre-order traversal


Delete (TREE, VAL) Step 1: Repeat Steps 2 to 4 while TREE !=
Step 1: IF TREE = NULLStep 2: Write TREE DATA
NULL Step 3: PREORDER(TREE
Write "VAL not found in the LEFT) Step 4:
tree"ELSE IF VAL < TREE PREORDER(TREE RIGHT)
DATA Delete(TREE->LEFT, [END OF LOOP]
VAL) Step 5: END
ELSE IF VAL > TREE DATA
Delete(TREE RIGHT, VAL) in-order traversal
ELSE IF TREE LEFT AND TREE RIGHT Step 1: Repeat Steps 2 to 4 while TREE !=
SET TEMP = findLargestNode(TREE NULLStep 2: INORDER(TREE LEFT)
LEFT)SET TREE DATA = TEMP Step 3: Write TREE DATA
DATA Delete(TREE LEFT, TEMP Step 4: INORDER(TREE
DATA) RIGHT)[END OF LOOP]
ELSE Step 5: END
SET TEMP = TREE
IF TREE LEFT = NULL AND TREE RIGHT Post-order traversal
= NULLSET TREE = NULL Step 1: Repeat Steps 2 to 4 while TREE !=
ELSE IF TREE NULLStep 2: POSTORDER(TREE LEFT)
LEFT != NULL SET Step 3: POSTORDER(TREE RIGHT)
TREE = TREELEFT Step 4: Write TREE
ELSE DATA[END OF
SET TREE = TREE LOOP]
RIGHT[END OF IF] Step 5: END
FREE
TEMP
[END OF
IF]
Step 2: END
to determine the height of a binary search tree to calculate the total number of internal nodes
in a binary search tree
Height (TREE)
Step 1: IF TREE = NULL totalInternalNodes(TREE
Return 0 )Step 1: IF TREE =
ELSE NULL
SET LeftHeight = Height(TREE Return
LEFT) SET RightHeight = TREE[END
Height(TREE RIGHT)IF LeftHeight > OF IF]
RightHeight IF TREE LEFT = NULL AND TREE RIGHT =
Return LeftHeight + NULL
1ELSE Return
Return RightHeight + ELSE
1[END OF IF] Return totalInternalNodes(TREE LEFT)
[END OF IF] +totalInternalNodes(TREE RIGHT) + 1
Step 2: END [END OF IF]
Step 2: END
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301
to calculate the number of nodes in a binary to calculate the total number of external nodes
search tree in a binary search tree
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

totalNodes(TREE) totalExternalNodes(TRE
Step 1: IF TREE = E)Step 1: IF TREE =
NULL NULL
Return o Return 0
ELSE ELSE IF TREE LEFT = NULL AND TREE
Return totalNodes(TREE LEFT) RIGHT = NULL
+ totalNodes(TREE RIGHT) Return 1
+ 1[END OF IF] ELSE
Step 2: END Return totalExternalNodes(TREE LEFT) +
totalExternalNodes(TREE RIGHT)
[END OF IF]
Step 2: END
to find the largest node in a binary search tree to find the smallest node in a binary search tree

findLargestElement(TREE) findSmallestElement(TREE)
Step 1: IF TREE = NULL OR TREE RIGHT = Step 1: IF TREE = NULL OR TREE LEFT =
NULL NULL
Return Return
TREEELSE TREEELSE
Return findLargestElement(TREE Return findSmallestElement(TREE
RIGHT)[END OF IF] LEFT)[END OF IF]
Step 2: END Step 2: END

Program:

#include<stdio.h> }
#include<conio.h> if(val<parentptr->data)
#include<malloc.h> parentptr->left=ptr;
struct node else
{ parentptr->right=ptr;
int data; }
struct node *left; return tree;
struct node *right; }
}; struct node *smallest_element(struct node *tree)
struct node *tree=NULL; {
struct node *ins_element(struct node *,int); if((tree==NULL)||(tree->left==NULL))
struct node *search(struct node *,int); return tree;
struct node *smallest_element(struct node *); else
struct node *largest_element(struct node *); return(smallest_element(tree-
struct node *delete_element(struct node *); >left));
int height(struct node *); }
int internal_nodes(struct node *);
int external_node(struct node *); struct node *largest_element(struct node *tree)
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

int total_node(struct node *); {


int main() if((tree==NULL)||(tree->right==NULL))
{ return tree;
int ch,val,h1; else
struct node *ptr; return(largest_element(tree-
clrscr(); >right));
do{ }
printf("\n1.Insert\n2.Search\n3.Smallest
element\n4.Largest element\n5.Delete struct node *delete_element(struct node *tree)
element\n6.Height\n7.Internal nodes\n8.External {
nodes\n9.Total nodes\n10.Exit\n"); while(tree!=NULL)
printf("Enter your choice \n"); delete_element(tree->left);
scanf("%d",&ch); delete_element(tree->right);
switch(ch) free(tree);
{ return tree;
case 1: }
printf("\nEnter value of new
node"); int height(struct node *tree)
scanf("%d",&val); {
tree=ins_element(tree,val); int leftheight,rightheight;
break; if(tree==NULL)
case 2: return 0;
printf("\nEnter element to be leftheight=height(tree->left);
searched"); rightheight=height(tree->right);
scanf("%d",&val); if(leftheight>rightheight)
tree=search(tree,val); return (leftheight+1);
break; else
case 3: return (rightheight+1);
ptr=smallest_element(tree); }
printf("\nSmallest element is
%d",ptr->data); int external_node(struct node *tree)
break; {
case 4: if(tree==NULL)
ptr=largest_element(tree); return 0;
printf("\nLargest element is else if((tree->left==NULL)&&(tree-
%d",ptr->data); >right==NULL))
break; return 1;
case 5: else
tree=delete_element(tree); return(external_node(tree-
break; >left)+external_node(tree->right));
case 6: }
h1=height(tree);
printf("\nThe height of the tree is int internal_node(struct node *tree)
%d",h1); {
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

break; if((tree==NULL)||((tree-
case 7: >left==NULL)&&(tree->right==NULL)))
printf("\nTotal number of return 0;
internal nodes is %d",internal_node(tree)); else
break; return(internal_node(tree-
case 8: >left)+internal_node(tree->right)+1);
printf("\nTotal number of }
external nodes is %d",external_node(tree));
break; int total_node(struct node *tree)
case 9: {
printf("\nTotal number of nodes if(tree==NULL)
is %d",total_node(tree)); return 0;
break; else
} return(total_node(tree-
}while(ch!=10); >left)+total_node(tree->right)+1);
getch(); }
return 0;
}
struct node *search(struct node *tree,int val)
struct node *ins_element(struct node *tree,int {
val) if((tree->data==val)||(tree==NULL))
{ return tree;
struct node *ptr,*nodeptr,*parentptr; if(val<tree->data)
ptr=(struct node *)malloc(sizeof(struct search(tree->left,val);
node)); else
ptr->data=val; search(tree->right,val);
ptr->left=NULL; return 0;
ptr->right=NULL; }
if(tree==NULL)
{ tree=ptr;
tree->left=NULL;
tree->right=NULL;
}
else
{parentptr=NULL;
nodeptr=tree;
while(nodeptr!=NULL)
{parentptr=nodeptr;
if(val<nodeptr->data)
nodeptr=nodeptr->left;
else
nodeptr=nodeptr->right;
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 9

Aim: Write a program to implement bubble sort.

Theory:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if
they are in the wrong order. Bubble sort, sometimes referred to as sinking sort, is a simple sorting
algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and
swaps 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.

Algorithm:

begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort

Program:

#include <stdio.h> {
#include if (array[i] > array[j])
<conio.h> int {temp
main() = array[i];
{ array[i] = array[j];
int array[100], n, i, j, temp; array[j] = temp;
clrscr(); }
printf("Enter number of elements\n"); }
scanf("%d", &n); }
printf("Enter %d integers\n", n); printf("Sorted list:\n");
for (i = 0; i < n; i++) for (i = 0; i < n; i++)
scanf("%d", printf("%d\t", array[i]);
&array[i]);for (i = 0; i < getch();
n; i++) return 0;
{ }
for (j = 0 ; j < n - 1; j++)

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 10

Aim: Write a program to implement Quick Sort.

Theory:

QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array
around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.

1. Always pick first element as pivot.


2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.

The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array
as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x,
and put all greater elements (greater than x) after x. All this should be done in linear time.

Algorithm:

PARTITION (ARR, BEG, END, LOC)

Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, PIVOT = BEG, FLAG =0
Step 2: Repeat Steps 3 to 6 while FLAG =1
Step 3: Repeat while ARR[PIVOT] <= ARR[RIGHT] AND PIVOT !=
RIGHTSET RIGHT = RIGHT - 1
[END OF LOOP]

Step 4: IF PIVOT =
RIGHTSET FLAG = 1
ELSE IF ARR[PIVOT] >
ARR[RIGHT] SWAP ARR[PIVOT]
with ARR[RIGHT]SET PIVOT =
RIGHT
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

[END OF IF]
Step 5: IF FLAG = 0
Repeat while ARR[PIVOT] >= ARR[LEFT] AND PIVOT !=
LEFTSET LEFT = LEFT + 1
[END OF LOOP]
Step 6: IF PIVOT =
LEFTSET FLAG = 1
ELSE IF ARR[PIVOT] <
ARR[LEFT] SWAP ARR[PIVOT]
with ARR[LEFT]
SET PIVOT =
LEFT[END OF
IF] [END OF IF]
Step 7: [END OF LOOP]
Step 8: END
QUICK_SORT (ARR, BEG, END)

Step 1: IF (BEG < END)


CALL PARTITION (ARR, BEG, END,
PIVOT)CALL QUICKSORT(ARR, BEG,
PIVOT - 1) CALL QUICKSORT(ARR,
PIVOT + 1, END) [END OF IF]
Step 2: END

Program:

#include <stdio.h> if(pivot==right)


#include <conio.h> flag =1;
#define size 100 else if(a[pivot]>a[right])
int partition(int a[], int beg, int end); {
void quick_sort(int a[], int beg, int end); temp = a[pivot];
void main() a[pivot] = a[right];
{ a[right] = temp;
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

int arr[size], i, n; pivot = right;


clrscr(); }
printf("\n Enter the number of elements in the if(flag!=1)
array: "); {
scanf("%d", &n); while((a[pivot] >= a[left]) && (pivot!=left))
printf("\n Enter the elements of the array: "); left++;
for(i=0;i<n;i++) if(pivot==left)
{ flag =1;
scanf("%d", &arr[i]); else if(a[pivot] <a[left])
} {
quick_sort(arr, 0, n-1); temp = a[pivot];
printf("\n The sorted array is: \n"); a[pivot] = a[left];
for(i=0;i<n;i++) a[left] = temp;
printf(" %d\t", arr[i]); pivot = left;
getch(); }
} }
int partition(int a[], int beg, int end) }
{ return pivot;
int left, right, temp, pivot, flag; }
pivot = left = beg; void quick_sort(int a[], int beg, int end)
right = end; {
flag = 0; int pivot;
while(flag != 1) if(beg<end)
{ {
while((a[pivot] <= a[right]) && (pivot!=right)) pivot = partition(a, beg, end);
right--; quick_sort(a, beg, pivot-1);
quick_sort(a, pivot+1, end);
}
}

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 11

Aim: Write a program to implement Binary Search.

Theory:

Binary search works on a principle of searching an element from 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.

Algorithm:

BINARY_SEARCH(A, ll, ul,


VAL) Step 1: [INITIALIZE]
SET BEG = ll END = ul,
POSITION = - 1
Step 2: Repeat Steps 3 and 4 while BEG <= END
Step 3: SET MID = (BEG + END)/2
Step 4: IF A[MID] =
VALSET POSITION
= MID PRINT
POSITION
Go to Step 6
ELSE IF A[MID] >
VALSET END =
MID - 1 ELSE
SET BEG = MID
+ 1[END OF IF]
[END OF LOOP]
Step 5: IF POSITION = -1
PRINT “VALUE IS NOT PRESENT IN THE
ARRAY”[END OF IF]
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Step 6: EXIT

Program:

#include<stdio.h> if(a[mid]==val)
#include<conio.h {
>int main() pos=mid+1;
{ printf("\nElement found at Position %d", pos);
int i,beg,end,mid,pos=-1,a[100],n,val; break;
clrscr(); }
printf("Enter number of elements "); else if(a[mid]>val)
scanf("%d",&n); end=mid-1;
printf("\nEnter sorted array"); else
for(i=0;i<n;i++) beg=mid+1;
scanf("%d",&a[i]); }
printf("\nEnter number to be searched"); if(pos==-1)
scanf("%d",&val); {
beg=0; printf("\n%d does not exist in
end=n-1; array",val);
while(beg<=end) }
{ getch();
mid=(beg+end)/2; return 0;
}

Outcome:
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Experiment No 12

Aim: Write a program to Implement Depth First Search and Breadth First Search.

Theory:

BFS:

Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree. The only catch
here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid
processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all
vertices are reachable from the starting vertex.

DFS:

Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch
here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid
processing a node more than once, we use a boolean visited array.

Algorithm:

#Algorithm for breadth-first #Algorithm for depth-first search


search Step 1: SET STATUS = 1 Step 1: SET STATUS = 1 (ready state) for each
(ready state)for each node in G node in G
Step 2: Enqueue the starting node A Step 2: Push the starting node A on the stack andset
and set its STATUS = 2 its STATUS = 2 (waiting state)
(waiting state) Step 3: Repeat Steps 4 and 5 until STACK is
Step 3: Repeat Steps 4 and 5 until emptyStep 4: Pop the top node N. Process it and
QUEUE is empty set its STATUS = 3 (processed state)
Step 4: Dequeue a node N. Process it Step 5: Push on the stack all the neighbours of N
and set its STATUS = 3 that
(processed state). are in the ready state (whose STATUS = 1)
Step 5: Enqueue all the neighbours of andset their STATUS = 2 (waiting state)
N that are in the ready state [END OF
(whose STATUS = 1) and LOOP]Step 6:
settheir STATUS = 2 EXIT
(waiting state)
[END OF
LOOP]
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

Step 6: EXIT

Program:

/****** BFS******/ /******* DFS********/

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


#define MAX 10 #define MAX 5
void breadth_first_search(int void depth_first_search(int
adj[][MAX],intvisited[],int start, int n) adj[][MAX],intvisited[],int start,int n)
{ {
int queue[MAX],rear = -1,front = -1, int
i;queue[++rear] = start; stack[MAX];
visited[start] = 1; int top = -1, i;
while(rear != front) printf("%c\t",start + 65);
{ visited[start] = 1;
start = queue[++front]; stack[++top] = start;
if(start == 4) while(top!=-1)
printf("5\t"); {
else start = stack[top];
printf("%c \t",start + 65); for(i = 0; i < n;
for(i = 0; i < n; i++) i++)
{ {
if(adj[start][i] == 1 && visited[i] == 0) if(adj[start][i] && visited[i] == 0)
{ {
queue[++rear] = i; stack[++top] = i;
visited[i] = 1; printf("%c\t", i +
} 65);visited[i] = 1;
} break;
}
}
}
}
int main()
if(i ==
{
MAX) top-
int visited[MAX] =
-;
{0};int
}
adj[MAX][MAX], i,
j,n; clrscr(); }
printf("\n Enter no of vertices in the graph: int main()
{
\n");
int adj[MAX][MAX];
int visited[MAX] = {0}, i, j, n;
clrscr();
!!Sab Ka Malik Atma!!
Vishwatmak Jangli Maharaj Ashram Trust
Atma Malik Institute of Technology and Research
At: Mohili, Post: Aghai, Via Kalyan, Dist.: Thane, 421301

scanf("%d",&n); printf("\n Enter number of vertices present in


printf("\n Enter the adjacency matrix: "); the graph: \n");
for(i = 0; i < n; i++) scanf("%d",&n);
for(j = 0; j < n; j++) printf("\n Enter the adjacency matrix: ");
scanf("%d", for(i = 0; i < n; i++)
&adj[i][j]); for(j = 0; j < n; j++)
breadth_first_search(adj,visited,0,n); scanf("%d", &adj[i][j]);
getch(); printf("DFS Traversal:
return 0; ");
} depth_first_search(adj,visited,0,n);
printf("\n");
Outcome: getch();
return 0;
}

Outcome:

You might also like