0% found this document useful (0 votes)
7 views80 pages

LAB - XBC206 - Data Structure Lab Manual

The document outlines the curriculum for the Data Structures Laboratory course for B.Sc. Computer Science students at Periyar Maniammai University, detailing the department's vision, mission, educational objectives, and program outcomes. It includes a list of experiments and aims to enhance students' technical skills in software development and digital design. Additionally, it provides specific programming tasks related to linked lists, including creation, insertion, deletion, and traversal operations.

Uploaded by

gokulvarma985
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)
7 views80 pages

LAB - XBC206 - Data Structure Lab Manual

The document outlines the curriculum for the Data Structures Laboratory course for B.Sc. Computer Science students at Periyar Maniammai University, detailing the department's vision, mission, educational objectives, and program outcomes. It includes a list of experiments and aims to enhance students' technical skills in software development and digital design. Additionally, it provides specific programming tasks related to linked lists, including creation, insertion, deletion, and traversal operations.

Uploaded by

gokulvarma985
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/ 80

DEPARTMENT OF SOFTWARE ENGINEERING

Periyar Nagar, Vallam Thanjavur - 613 403, Tamil Nadu, India Phone:
+91 - 4362 - 264600 Fax: +91- 4362 - 264660
Email: [email protected] Web: www. pmu.edu

XBC206 : DATA STRUCTURES LABORATORY

B.Sc. Computer Science

(I YEAR–II SEMESTER) (2023-2026)

Course InCharge HOD/SE


1. U. GOMATHI (Dr.D.Maghesh Kuar)
2. T. PARKAVI
Department of Software Engineering

DEPARTMENT VISION

To be a leading department in the field of software development and digital design


that offers the software education with the State-of-the-art skills. The Graduates will be
recognized as globally competent by their dynamic work and produce valuable digital
solutions for the society.

DEPARTMENT MISSION

DM1 To construct the software related technical skills among the students.

DM2 To practice the cutting-edge technologies in the various areas of digital design
and software development.

DM3 To contribute towards the betterment of the society by producing enhanced


software solutions through research.
DM4 To generate the spirit of inquiry, team work, novelty and professionalism
among the students.

Mapping of University Mission (UM) and Department Mission (DM)


DM1 DM2 DM3 DM4 Total
UM1 2 3 1 0 6
UM2 1 2 0 2 5
UM3 1 1 3 0 5
UM4 3 1 1 1 6
UM5 0 0 2 3 5

1-Low 2- Medium 3 – High


PROGRAMME EDUCATIONAL OBJECTIVES (PEO)

Based on the mission of the department, the programme educational objective is formulated as .

The B.Sc. Computer Science dedicated to produce graduates who have ability to

PEO1 evolve as globally proficient computer professionals by giving


enriched performance in problem solving, analysis and synthesis for
computer science related issues..

PEO2 exercise with contemporary tools and technologies to provide an effective

user friendly interface for the real time social concerns.


PEO3 communicate effectively in a multidisciplinary team and manage the
team members through the acquired leadership skills to achieve the target in time.

PEO4 handle the customers and stakeholders effectively with the awareness of
human values and ethical concerns.
PEO5 pursue lifelong learning through the cutting-edge Learning Management
Systems and thus satisfy the up-to-date industry expectations.

Mapping of Program Educational Objectives (PEOs) with Department Mission (DM)

B.Sc. (CS) PEO1 PEO2 PEO3 PEO4 Total


DM1 3 2 0 0 5
DM2 2 2 1 1 6
DM3 1 2 1 1 5
DM4 0 1 3 1 5
1- Low 2 – Medium 3-High

PROGRAMME OUTCOME (PO)


At the time of graduation, competency of the student is measured through the attainment of programme
outcomes. The quantification of programme outcomes attainment is measured through the assessment of
established course outcomes for each course.
PROGRAMME OUTCOMES

PO 1 identify and analyze the acquainted or unacquainted real time issues and afford
solution using the necessary computing, mathematical and basic science skill set.

PO 2 design and develop algorithms for providing an appropriate solution to gratify the
industrial and social needs.

PO 3 express ideas and thoughts effectively to the team members and customers
through written and oral communication.

PO 4 work jointly with different team members in order to complete the


agreed work in time.

PO 5 inspire and guide the team members using management skills to achieve the target
in an efficient and smooth way.

PO 6 provide a remarkable impact on the society by contributing resolutions to social


issues with the awareness of ethical responsibility by discriminating ethical
&unethical behaviors and understanding human, professional values&
responsibilities.
PO 7 utilize computer literacy in the learning and working places and self- adapt with
the changing environment by participating in learning activities throughout the
life.

PROGRAMMME SPECIFIC OUTCOME

PSO1 provide the professional user friendly interface with the help of state-of- the-art
tools and technologies.

PSO2 design the interactive& responsive web based and mobile applications.

Learning Objectives and Course Outcomes


Learning Objectives:

This course aims at

● Facilitating the student to understand the various concepts and functionalities of


Database Management Systems, the method and model to store data.
● How to manipulate through query languages, the effective designing of relational
database.
● How the system manages the concurrent usage of data in multi user
environment.
LIST OF EXPERIMENTS

S.No Experiment Page

No

1.1 Create a Linked List & Display the Elements in the List 6

1.2 Linked List operations insertion and deletion 8

1.3 Doubly Linked List 25

2.1 Stack operations in C 28

2.2 Infix expression to postfix conversion using stack 34

2.3 Queue 36

3. Binary tree traversal 39

4.1 Linear Search and Binary Search Algorithm 41

4.2 Insertion Sort 44

4.3 Bubble Sort 45

4.4 Quick Sort 46

5.1 Binary search tree creation, insertion and deletion operations 48

5.2 Breadth First Search (BFS) traversal of a graph 52

5.3 Depth First Search (DFS) traversal of a graph 57


Aim:
To write a c program to the creation of list of elements where the size of the list, elements to be inserted
and deleted is dynamically given as input.

Procedure

1. Node Definition:
● Define a structure (or class, depending on the programming language) that represents a node in the
linked list. This structure typically contains two components:
● Data: The actual data or value associated with the node.
● Next: A reference or pointer to the next node in the sequence.
2. Initialization:
● Create a head pointer that points to the first node in the list. Initially, the head can be set to NULL if
the list is empty.
3. Insertion:
● To insert a new node into the linked list:
● Create a new node with the desired data.
● Update the next pointer of the new node to point to the current first node.
● Update the head pointer to point to the new node.
4. Deletion:
● To delete a node from the linked list:
● Find the node to be deleted.
● Update the next pointer of the previous node to skip the node to be deleted.
● Free the memory allocated to the deleted node.

Program Coding:

/*
* C program to create a linked list and display the elements in the list
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

void main()
{
struct node
{
int num;
struct node *ptr;
};
typedef struct node NODE;

NODE *head, *first, *temp =


0; int count = 0;
int choice = 1;

first = 0;
clrscr();

while (choice)
{
head = (NODE *)malloc(sizeof(NODE));
printf("Enter the data item\n");
scanf("%d", &head-> num);
if (first != 0)
{
temp->ptr =
head; temp =
head;
}
else
{
first = temp = head;
}
fflush(stdin);
printf("Do you want to continue(Type 0 or 1)?\n");
scanf("%d", &choice);

temp->ptr = 0;
/* reset temp to the beginning */
temp = first;
printf("\n status of the linked list is\n");
while (temp != 0)
{
printf("%d=>", temp->num);
count++;
temp = temp -> ptr;
}
printf("NULL\n");
printf("No. of nodes in the list = %d\n", count);
getch();

}
Output:

Result:
Thus to write a c program to the creation of list of elements where the size of the list, elements to be
inserted and deleted is dynamically given as input has been verified.
Aim:
To implement a C program to insert and delete elements from the singly linked list.

Procedure

1. Node Definition:
a. Define a structure (or class, depending on the programming language) that represents a node in the
linked list. This structure typically contains two components:
i. Data: The actual data or value associated with the node.
ii. Next: A reference or pointer to the next node in the sequence.
2. Initialization:
a. Create a head pointer that points to the first node in the list. Initially, the head can be set to NULL if
the list is empty.
3. Insertion:
a. To insert a new node into the linked list:
i. Create a new node with the desired data.
ii. Update the next pointer of the new node to point to the current first node.
iii. Update the head pointer to point to the new node.
4. Deletion:
● To delete a node from the linked list:
● Find the node to be deleted.
● Update the next pointer of the previous node to skip the node to be deleted.
● Free the memory allocated to the deleted node.

Program:
#include&lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include&lt;conio.h&gt;
void create();
void display();
void insert_begin();
void insert_end();
void insert_pos();
void delete_begin();
void delete_end();
void delete_pos();

struct node
{
int info;
struct node *next;
};
struct node *start=NULL;
void main()
{
int choice;

clrscr();
while(1)
{

printf(&quot;\n MENU \n&quot;);


printf(&quot;\n 1.Create \n&quot;);
printf(&quot;\n 2.Display \n&quot;);
printf(&quot;\n 3.Insert at the beginning \n&quot;);
printf(&quot;\n 4.Insert at the end \n&quot;);
printf(&quot;\n 5.Insert at specified position \n&quot;);
printf(&quot;\n 6.Delete from beginning \n&quot;);
printf(&quot;\n 7.Delete from the end \n&quot;);
printf(&quot;\n 8.Delete from specified position \n&quot;);
printf(&quot;\n 9.Exit \n&quot;);
printf(&quot;\n \n&quot;);
printf(&quot;Enter your choice:\t&quot;);
scanf(&quot;%d&quot;,&amp;choice);

switch(choice)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert_begin();
break;
case 4:
insert_end();
break;
case 5:
insert_pos();
break;
case 6:
delete_begin();
break;
case 7:
delete_end();
break;
case 8:
delete_pos();
break;

case 9:
exit(0);
break;

default:

printf(&quot;\n Wrong Choice:\n&quot;);

break;

}
}
getch();
}
void create()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf(&quot;\nOut of Memory Space:\n&quot;);
exit(0);
}
printf(&quot;\nEnter the data value for the node:\t&quot;);
scanf(&quot;%d&quot;,&amp;temp-&gt;info);
temp-&gt;next=NULL;
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr-&gt;next!=NULL)
{
ptr=ptr-&gt;next;
}
ptr-&gt;next=temp;
}
}
void display()
{
struct node *ptr;
if(start==NULL)
{
printf(&quot;\nList is empty:\n&quot;);
return;
}
else
{
ptr=start;
printf(&quot;\nThe List elements are:\n&quot;);
while(ptr!=NULL)
{
printf(&quot;%dt&quot;,ptr-&gt;info );
ptr=ptr-&gt;next ;
}
}
}

void insert_begin()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf(&quot;\nOut of Memory Space:\n&quot;);
return;
}
printf(&quot;\nEnter the data value for the node:\t&quot; );
scanf(&quot;%d&quot;,&amp;temp-&gt;info);
temp-&gt;next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
temp-&gt;next=start;
start=temp;
}
}
void insert_end()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf(&quot;\nOut of Memory Space:\n&quot;);
return;
}
printf(&quot;\nEnter the data value for the node:\t&quot; );
scanf(&quot;%d&quot;,&amp;temp-&gt;info );
temp-&gt;next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr-&gt;next !=NULL)
{
ptr=ptr-&gt;next ;
}
ptr-&gt;next =temp;
}
}
void insert_pos()
{

struct node *ptr,*temp;


int i,pos;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf(&quot;\nOut of Memory Space:\n&quot;);
return;
}
printf(&quot;\nEnter the position for the new node to be inserted:\t&quot;);
scanf(&quot;%d&quot;,&amp;pos);
printf(&quot;\nEnter the data value of the node:\t&quot;);
scanf(&quot;%d&quot;,&amp;temp-&gt;info) ;
temp-&gt;next=NULL;
if(pos==0)
{
temp-&gt;next=start;
start=temp;
}
else
{
for(i=0,ptr=start;i&lt;pos-1;i++)
{
ptr=ptr-&gt;next;
if(ptr==NULL)
{
printf(&quot;\nPosition not found:[Handle with care]\n&quot;);
return;
}
}
temp-&gt;next =ptr-&gt;next ;
ptr-&gt;next=temp;
}
}
void delete_begin()
{
struct node *ptr;
if(ptr==NULL)
{
printf(&quot;\nList is Empty:\n&quot;);
return;
}
else
{
ptr=start;
start=start-&gt;next ;
printf(&quot;\nThe deleted element is :%d\t&quot;,ptr-&gt;info);
free(ptr);
}
}

void delete_end()
{
struct node *temp,*ptr;
if(start==NULL)
{
printf(&quot;\nList is Empty:&quot;);
exit(0);
}
else if(start-&gt;next ==NULL)
{
ptr=start;
start=NULL;
printf(&quot;\nThe deleted element is:%d\t&quot;,ptr-&gt;info);
free(ptr);
}
else
{
ptr=start;
while(ptr-&gt;next!=NULL)
{
temp=ptr;
ptr=ptr-&gt;next;
}
temp-&gt;next=NULL;
printf(&quot;\nThe deleted element is:%d\t&quot;,ptr-&gt;info);

free(ptr);
}
}
void delete_pos()
{
int i,pos;
struct node *temp,*ptr;
if(start==NULL)
{
printf(&quot;\nThe List is Empty:\n&quot;);
exit(0);
}
else
{
printf(&quot;\nEnter the position of the node to be deleted:\t&quot;);
scanf(&quot;%d&quot;,&amp;pos);
if(pos==0)
{
ptr=start;
start=start-&gt;next ;
printf(&quot;\nThe deleted element is:%d\t&quot;,ptr-&gt;info );
free(ptr);
}
else
{
ptr=start;
for(i=0;i&lt;pos;i++) { temp=ptr; ptr=ptr-&gt;next ;
if(ptr==NULL)
{
printf(&quot;\nPosition not Found:\n&quot;);
return;
}
}
temp-&gt;next =ptr-&gt;next ;
printf(&quot;\nThe deleted element is:%d\t&quot;,ptr-&gt;info );
free(ptr);
}
}
}

Output:
Result:

Thus the C program for the inserting and deleting the elements in the linked list is
implemented and verified successfully.
Aim:
To implement C Program finds the largest element in a doubly linked list.

Procedure :

Define the Node Structure:


● Create a structure to represent a node in the doubly linked list.
● Each node should have a data field and two pointers: one for the next node and one for the
previous node.
Initialize the Doubly Linked List:
● Create functions to initialize an empty doubly linked list. This involves setting the head pointer to
NULL.
Insertion:
● Implement functions to insert nodes into the doubly linked list at various positions (beginning, end,
or a specific position).
● Update the next and prev pointers accordingly.
Deletion:
● Implement functions to delete nodes from the doubly linked list at various positions.
● Update the next and prev pointers accordingly.
Program:
/*
* C Program to Find the Largest Element in a Doubly Linked List
*/
#include <stdio.h>
#include <conio.h>

struct node
{
int num;
struct node *next;
struct node
*prev;
};

void create(struct node **);


int max(struct node *);
void release(struct node **);

void main()
{
struct node *p =
NULL; int n;
printf("Enter data into the
list\n"); create(&p);
n = max(p);
printf("The maximum number entered in the list is %d.\n",
n); release (&p);
getch();
}

int max(struct node *head)


{
struct node *max, *q;
q = max = head;
while (q !=
NULL)
{
if (q->num > max->num)
{
max = q;
}
q = q->next;
}
return (max->num);
}
void create(struct node **head)
{
int c, ch;
struct node *temp, *rear;

do
{
printf("Enter number:
"); scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct
node)); temp->num = c;
temp->next = NULL;
temp->prev =
NULL; if (*head ==
NULL)
{
*head = temp;
}
else
{
rear->next = temp;
temp->prev =
rear;
}
rear = temp;
printf("Do you wish to continue [yes:1/No:0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}

void release(struct node **head)


{
struct node *temp = *head;

*head = (*head)->next;
while ((*head) !=
NULL)
{
free(temp);
temp = *head;
(*head) = (*head)->next;
}
}

OUTPUT:
Enter data into the list
Enter number: 10
Do you wish to continue [yes:1/No:0]: 1
Enter number: 50
Do you wish to continue [yes:1/No:0]: 1
Enter number: 41
Do you wish to continue [yes:1/No:0]: 1
Enter number: 67
Do you wish to continue [yes:1/No:0]: 0

The maximum number entered in the list is 67.

Result:

Thus the program successfully completed.


Aim:
To implement C program for stack using array.

Procedure :
1. Initialization:
● Create an empty stack. You can use an array or a linked list to implement a stack, depending on your
preference and the programming language.
2. Push (Insert):
● To add an element to the stack (push operation):
● Check if the stack is full (if using a fixed-size array implementation).
● If not full, add the element to the top of the stack.
● Update the top pointer to the new top element.
3. Pop (Delete):
● To remove the top element from the stack (pop operation):
● Check if the stack is empty.
● If not empty, remove the element from the top of the stack.
● Update the top pointer to the next element in the stack.
4. Peek (Top):
● To view the top element without removing it:
● Check if the stack is empty.
● If not empty, retrieve the element at the top of the stack.
5. isEmpty:
● Check if the stack is empty.
6. isFull (if using a fixed-size array):
● Check if the stack is full.
7. Size:
● Get the current number of elements in the stack.
Program:
#include<stdio.h>
#include<conio.h>
#define Size 4

int Top=-1, stack[Size]; //global declaration


void Push(); //function prototype
void Pop();
void show();

int main()
{
int choice;
clrscr();
while(1)
{
printf("\nOperations performed by Stack");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice:");
scanf("%d",&choice);

switch(choice)
{
case 1: Push();
break;
case 2: Pop();
break;
case 3: show();
break;
case 4: exit(0);

default: printf("\nInvalid choice!!");


}
}
}

void Push()
{
int x;

if(Top==Size-1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
stack[Top]=x;
}
}

void Pop()
{
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
p
ri
nt
}
f(
}
"\
n
P
o
p
p
e
d
el
e
m
e
nt
:
%
d
",
st
a
c
k
[
T
o
p
])
;
T
o
p
=
T
o -
p 1;

void show()
{
int i;

if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
p
ri
n
} tf
(
}
"\
n
E
l
e
m
e
n
ts
p
r
e
s
e
n
t
i
n
t
h
e
st
a
c
k
:
\
n
"
);
f
o
r(
i
=
T
o
p
;i
>
=
0
;-
-i
)
printf("%d\n",stack[i]);
OUTPUT:
Result:
Thus the C program to implement stack using array has been executed and verified successfully.
Aim:
To implement the C program for Infix expression to postfix conversion using stack.

Procedure :

Stack Initialization:
● Define a structure for the stack and create functions to initialize, check for empty or full, push, and pop
elements from the stack.
Evaluate Postfix Expression:
● Create a function to evaluate a postfix expression using a stack.
Infix to Postfix Conversion:
● Create a function to convert an infix expression to postfix notation.
Get Operator Precedence:
● Create a function to get the precedence of an operator for proper infix to postfix conversion.
Display Result:
● Create a function to display the result of the postfix expression.

Program

#include<stdio.h>
#include<conio.h>
char stack[20];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x ==
'-') return 1;
if(x == '*' || x ==
'/') return 2;
return 0;
}
void main()
{
char exp[100];
char *e, x;
clrscr();
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')

{
while((x = pop()) !=
'(') printf("%c ",
x);
}
else
{
while(priority(stack[top]) >=
priority(*e)) printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}
getch();
}

Output:
Result:
Thus the C program to implement the application of stack using array has been executed and verified
successfully.
Aim:
To implement the C program for queue using array.

1. Initialization:
Create an empty queue. You can use an array or a linked list to implement a queue, depending on
your preference and the programming language.
2. Enqueue (Insert):
To add an element to the queue (enqueue operation):
● Check if the queue is full (if using a fixed-size array implementation).
● If not full, add the element to the rear of the queue.
● Update the rear pointer to the new rear element.
3. Dequeue (Delete):
To remove the front element from the queue (dequeue operation):
● Check if the queue is empty.
● If not empty, remove the element from the front of the queue.
● Update the front pointer to the next element in the queue.
4. Front (Peek):
To view the front element without removing it:
● Check if the queue is empty.
● If not empty, retrieve the element at the front of the queue.
5. isEmpty:
Check if the queue is empty.
6. isFull (if using a fixed-size array):
Check if the queue is full.
7. Size:
Get the current number of elements in the queue.

Program:
#include <stdio.h>
#include<conio.h>
#define MAX 50

void insert();
void delete();
void display();

int queue_array[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int choice;
clrscr();
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice :
"); scanf("%d", &choice);
switch(choice)
{
case 1: i
n
s
case 2: e
r
t
case 3: (
)
;
case 4: b
r
e
a
k
;

d
e
l
e
t
e
(
)
;
b
r
e
a
k
;

d
i
s
p
l
a
y
(
)
;
b
r
e
a
k
;

exit(1);
default:
printf("Wrong choice \n");
}
}
getch();
}
void insert()
{
int item;
if(rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if(front== - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
void delete()
{
if(front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if(front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for(i = front; i <= rear;
i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
Output:
Result:
Thus the C program to implement queue using array has been executed and verified successfully.
Aim:
To implement the C program to visit each node in a binary tree using tree traversal techniques.

Procedure

1. Initialization:
● Create an empty binary tree.
2. Insertion:
● To insert a new element into the binary tree:
● Start at the root.
● If the tree is empty, create a new node as the root.
● Otherwise, traverse the tree from the root:
● If the value to be inserted is less than the current node's value, move to the left child.
● If the value is greater, move to the right child.
● Repeat the process until an empty spot is found, then insert the new node.
3. Deletion:
● To delete a node from the binary tree:
● Locate the node to be deleted.
● If the node has no children, simply remove it.
● If the node has one child, replace the node with its child.
● If the node has two children:
● Find the node's in-order successor (the smallest node in the right subtree).
● Replace the node's value with the in-order successor's value.
● Delete the in-order successor node.
4. Minimum and Maximum:
● To find the minimum value in the binary tree, follow the left child pointers until you reach a leaf
node.
● To find the maximum value, follow the right child pointers until you reach a leaf node.

//Binary tree traversal


#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* left,* right;
};
struct node* create()
{
int a;
struct node* newnode;
newnode = (struct node*) malloc(sizeof(struct node));
printf("Enter the data(-1 for no data)");
scanf("%d", &a);
if(a==-1)
{
return 0;
}
newnode->data=a;
printf("Enter left child of %d",a);
newnode->left=create();
printf("Enter right child of %d",a);
newnode->right=create();
return newnode;
}
void preorder(struct node* root)
{
if(root==0)
{
return;
}
printf(" %d",
root->data);
preorder(root->left);
preorder(root->right);
}

void inorder(struct node* root)


{
if(root==0)
{
return;
}
inorder(root->left);
printf(" %d",
root->data);
inorder(root->right);
}

void postorder(struct node* root)


{
if(root==0)
{
return;
}
postorder(root->left);
postorder(root->right);
printf(" %d",
root->data);
}
void main()
{
struct node* root;
clrscr();
root=0;
root=create();
printf("\nPreorder traversal:");
preorder(root);
printf("\ninorder traversal:");
inorder(root);
printf("\nPostorder traversal:");
postorder(root);
getch();
}

Output:

Result:
Thus the C program to implement the tree traversals in a binary tree has been executed and verified
successfully.
Aim:
To implement a C Program to search an element in a list using linear search and binary search
algorithm.

Procedure :
1. Linear Search:
● Create a function linear_search that takes a list (arr) and an element to search for (x) as
parameters.
● Use a loop to iterate through each element in the list.
● Check if the current element is equal to the target element (x).
● If found, return the index of the element.
● If the loop completes without finding the element, return -1 to indicate that the element is not in the
list.
2. Binary Search:
● Create a function binary_search that assumes the input list is sorted and takes a sorted list (arr)
and an element to search for (x) as parameters.
● Initialize two pointers (low and high) to represent the range of the search.
● Use a while loop to continue searching while the low pointer is less than or equal to the high
pointer.
● Calculate the middle index (mid) of the current search range.
● Check if the element at the middle index is equal to the target element (x).
● If found, return the index of the element.
● If the target element is less than the middle element, update the high pointer to narrow the search to
the lower half.
● If the target element is greater than the middle element, update the low pointer to narrow the search
to the upper half.
● If the loop completes without finding the element, return -1 to indicate that the element is not in the
list.
Program:
/* Program to implement linear search and Binary search */

#include <stdio.h>
#include <conio.h>
void main()
{
/* Declare variables - array_of_number, search_key, i, j, low, high*/
int array[100],search_key,i,j,n,low,high,location,choice;
void linear_search(int search_key,int array[100],int n);
void binary_search(int search_key,int array[100],int
n); clrscr();
/* read the elements of array */
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
/* Get the Search Key element for Linear Search */
printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key);
/* Choice of Search Algorithm */
printf("
\n"); printf("1.LINEAR
SEARCH\n"); printf("2.BINARY
SEARCH\n");
printf(" \n");
printf("ENTER YOUR
CHOICE:");
scanf("%d",&choice)
; switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
binary_search(search_key,array,n);
break;
default:
exit(0);
}
getch();
}
/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{
/*Declare Variable */
int i,location;
for(i=1;i<=n;i++
)
{
if(search_key == array[i])
{
location = i;

printf(" \n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf(" \n");
}
}
}
/* Binary Search to find Search Key */
void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high;
low = 1;
high = n;
mid = (low +
high)/2; i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1;
high = mid+1;
mid = (low+high)/2;
}
else
{
low =
mid+1; high
= n;
mid = (low+high)/2;
}
}
printf("
_\n"); printf("location=%d\t",mid);
printf("Search_Key=%d Found!\n",search_key);
printf("
_\n");
}
Output

ENTER THE SIZE OF THE ARRAY:6


ENTER THE ELEMENTS OF THE ARRAY:
45
6
86
23
64
77
ENTER THE SEARCH KEY:86
1. LINEAR SEARCH
2. BINARY SEARCH

ENTER YOUR CHOICE:2

Location =3 Search_Key = 86 Found!


Result:
Thus the C program to search an element in a list using linear search and binary search
algorithm has been executed and verified successfully.
Aim:
To write a C program to sort the list of elements using insertion sort algorithm.

Procedure :
1. Start with the Second Element:
● Begin the sorting process from the second element (index 1) because the first element (at
index 0) is considered already sorted.
2. Compare and Insert:
● Compare the current element with the elements on its left.
● Insert the current element into its correct position in the sorted part of the array by shifting
larger elements to the right.
3. Repeat:
● Repeat the process for each unsorted element in the array until the entire array is sorted.

Program:
// C program for
insertion sort
#include <math.h>
#include <stdio.h>

/* Function to sort an array using


insertion sort*/ void insertionSort(int
arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
//arr[1]=11 j = i
- 1; //0 , arr[0]
= 12

/* Move elements of
arr[0..i-1], that are greater
than key, to one position
ahead of their current
position */
while (j >= 0 && arr[j] >
key) { arr[j + 1] =
arr[j]; //12, arr[1] = 12 j
= j - 1; // 0-1 = -1
}
arr[j + 1] = key; // arr[0] = 11
}
}
// A utility function to print an
array of size n void printArray(int
arr[], int n)
{
int i;
for (i = 0; i
< n; i++)
printf("%
d ",
arr[i]);
printf("\n");
}

void main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) /
sizeof(arr[0]); clrscr();
insertionS
ort(arr, n);
printArray
(arr, n);
getch();
}
Output:

5 6 11 12 13

Result:
Thus the C program to sort the list using insertion sort has been executed and verified
successfully.
Aim:
To write a C program to sort the list of elements using bubble sort algorithm.

Procedure :

1. Start from the Beginning:


● Start from the beginning of the array.
2. Compare and Swap:
● Compare each pair of adjacent elements.
● If they are in the wrong order (the element on the left is greater than the element on the right), swap
them.
3. One Pass:
● Complete one pass through the array, ensuring that the largest element has been moved to its correct
position (at the end of the array).
4. Repeat:
● Repeat steps 2 and 3 for each element in the array until the entire array is sorted.

Program:
// C program for implementation of Bubble sort
#include <stdio.h>
#include<conio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
void main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n =
sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
getch();
}
Output:
Sorted array:
11 12 22 25 34 64 90
Result:
Thus the C program to sort the list using bubble sort has been executed and verified
successfully.
Aim:
To write a C program to sort the list of elements using quick sort algorithm.

Procedure

1. Choose a Pivot:
● Select a pivot element from the array. The choice of the pivot can be arbitrary (e.g., the last element,
the middle element, or a random element).
2. Partition:
● Partition the array into two sub-arrays: elements less than the pivot and elements greater than the
pivot.
3. Recursively Sort Sub-arrays:
● Recursively apply the Quick Sort algorithm to the two sub-arrays.
4. Combine:
● Combine the sorted sub-arrays and the pivot back into a single sorted array.

Program:
#include <stdio.h>
#include<conio.h>
void quick_sort(int[],int,int);
int partition(int[],int,int);

void main()
{
int a[50],n,i;
clrscr();
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array
elements:"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick_sort(a,0,n-1);
printf("\nArray after sorting:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}

void quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u)
;
}
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;
do
{
do
i++;
while(a[i]<v&&i<=u)
; do
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
Output:

Result:
Thus the C program to sort the list using quick sort has been executed and verified
successfully.
Aim:

To write a C program to create a binary search tree and insert and delete the element from
the tree.

Procedure:

Define the Node Structure:


● Create a structure to represent a node in the Binary Search Tree.
● Each node should contain a data field, a pointer to the left child, and a pointer to the right child.

Initialization:
● Create a pointer to represent the root of the BST, initially set to NULL.

Insertion:
● Implement a function to insert a new node with a given value into the BST.
● If the tree is empty, create a new node as the root.
● Otherwise, traverse the tree based on the comparison of values to find the correct
position for insertion.

Program
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int key;
struct node *left;
struct node *right;
}Node;
/*for creating new node */
Node * newNode(int key){

Node *temp = (Node


*)malloc(sizeof(Node)); temp->key = key;
temp->left = NULL;
temp->right = NULL;

return temp;
}
/*for inserting the key, newNode is the node needed to be inserted */
Node * insert(Node *p, Node *nwNode){
if(!p){
printf("Key %d\tinserted\n", nwNode->key);
return nwNode;
}

if(nwNode->key >
p->key){ insert(p->right,
nwNode); if(!(p->right))
p->right = nwNode;
}
else{
insert(p->left,
nwNode); if(!(p->left))
p->left = nwNode;
}

return p;
}
/* for searching the key */
void search(Node *p, int searchKey){
if(!p){
printf("No key found for value - %d.\n", searchKey);
return ;
}

if(p->key == searchKey){
printf("Key %d\tfound\n", searchKey);
}

else if(p->key < searchKey)


search(p->right, searchKey);
else
search(p->left, searchKey);

}
/* inorder successor in BST will be the minimum key in right subtree */
Node * getInSuccessor(Node *p){
while(p->left != NULL)
p = p->left; //this will give the minimum key
return p;
}

Node * deletion(Node *p, int delKey){


struct node *temp;
if(!p){
printf("Unable to delete. No such key exists.\n");
return p;
}
else if(delKey > p->key)
p->right = deletion(p->right, delKey);
else if(delKey < p->key)
p->left = deletion(p->left, delKey);

/* executing else means get the key */


else{
/* node has one child or no child */
if(p->left == NULL){
temp =
p->right;
free(p);
return temp;
}
else if(p->right ==
NULL){ temp = p->left;

free(p);
return
temp;
}

/* node with two children, interchange with inorder successor */


temp = getInSuccessor(p->right);
p->key = temp->key;
p->right = deletion(p->right, temp->key); // Delete the inorder successor
}
return p;
}
/* Preorder traversal that outputs key in non-decreasing order*/
void traversePreorder(Node *p){
if(!p)
return ;
printf("%d ", p->key);
traversePreorder(p->left);
traversePreorder(p->right)
;
}
/* Inorder traversal that outputs key in non-decreasing order*/
void traverseInorder(Node *p){
if(!p)
return ;
traverseInorder(p->left);
printf("%d ", p->key);
traverseInorder(p->right);
}
/* Postorder traversal that outputs key in non-decreasing order*/
void traversePostorder(Node *p){
if(!p)
return ;
traversePostorder(p->left);
traversePostorder(p->right)
; printf("%d ", p->key);
}

void main(void)
{
Node *root =
NULL; Node
*newRoot; clrscr();
root = insert(root, newNode(50));
insert(root, newNode(80));
insert(root, newNode(30));
insert(root, newNode(40));
insert(root, newNode(20));
insert(root, newNode(100));
search(root, 50);
search(root, 10);

newRoot = deletion(root, 50);


if(newRoot){
printf("Successfully deleted node. Now tree root node is - %d.\n", newRoot->key);
}
search(root, 50);
printf("Preorder Traversal: ");
traversePreorder(root);
printf("\nInorder Traversal: ");
traverseInorder(root);
printf("\nPostorder Traversal: ");
traversePostorder(root);

getch();
}

OUTPUT

Result:
Thus the C program to create a binary search tree and insert and delete the element from the
tree has been executed and verified successfully.
Aim:
To write a C program to implement the Breadth First Search (BFS) traversal for directed
Graph using a Queue.

1. Create a Queue:
● Create an empty queue to keep track of the vertices to be processed.
2. Enqueue the Source Vertex:
● Enqueue the source vertex into the queue.
3. Mark the Source Vertex as Visited:
● Mark the source vertex as visited to avoid revisiting it.
4. While the Queue is Not Empty:
● While the queue is not empty, do the following steps:
● Dequeue a vertex from the queue.
● Process the dequeued vertex (print it or perform some other operation).
● Enqueue all the unvisited neighbors of the dequeued vertex.
● Mark each visited neighbor as visited.
5. Repeat Until the Queue is Empty:
● Repeat the process until the queue is empty.

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

#define MAX 100

#define initial 1
#define waiting 2
#define visited 3

int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);

int queue[MAX], front = -1,rear = -1;


void insert_queue(int vertex);
int delete_queue();
int isEmpty_queue();
void main()
{
clrscr();
create_graph();
BF_Traversal();
getch();
}

void BF_Traversal()
{
int v;
for(v=0; v<n;
v++) state[v] =
initial;
printf("Enter Start Vertex for BFS: \n");
scanf("%d", &v);
BFS(v);
}

void BFS(int v)
{
int i;
insert_queue(v);
state[v] = waiting;
while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;
for(i=0; i<n; i++)
{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}
void insert_queue(int vertex)
{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}

int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}

int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}
delete_item = queue[front];
front = front+1;
return delete_item;
}

void create_graph()
{
int count,max_edge,origin,destin;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edge = n*(n-1);

for(count=1; count<=max_edge; count++)


{
printf("Enter edge %d( -1 -1 to quit ) : ",count);
scanf("%d %d",&origin,&destin);
if((origin == -1) && (destin == -1))
break;

if(origin>=n || destin>=n || origin<0 || destin<0)


{
printf("Invalid
edge!\n"); count--;
}
else
{
adj[origin][destin] = 1;
}
}
}

Output:

Result:
Thus the C program to Breadth First Search (BFS) traversal for directed Graph using a Queue
has been executed and verified successfully.
Aim:

To write a C program to implement DFS Algorithm for Connected Graph using a stack.

DFS:
Depth First Search (DFS) algorithm traverses a graph in a depth ward motion and uses a stack to
remember to get the next vertex to start a search, when a dead end occurs in any iteration.
It employs the following rules.
▪ Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.

▪ Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the
vertices from the stack, which do not have adjacent vertices.)

▪ Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

Program:
/* C Program to implement DFS Algorithm for Connected Graph */

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

#define MAX 100

#define initial 1
#define visited 2

int n; /* Number of nodes in the graph */


int adj[MAX][MAX]; /*Adjacency
Matrix*/ int state[MAX]; /*Can be initial or
visited */

void DF_Traversal();
void DFS(int v);
void create_graph();

int stack[MAX];
int top = -1;
void push(int
v); int pop();
int isEmpty_stack();

void main()
{
clrscr();
create_graph();
DF_Traversal();
getch();

}/*End of main()*/

void DF_Traversal()
{
int v;

for(v=0; v<n; v++)


state[v]=initial;

printf("\nEnter starting node for Depth First Search : ");


scanf("%d",&v);
DFS(v);
printf("\n");
}/*End of DF_Traversal( )*/

void DFS(int v)
{
int i;
push(v);
while(!isEmpty_stack())
{
v = pop();
if(state[v]==initial)
{
printf("%d ",v);
state[v]=visited
;
}
for(i=n-1; i>=0; i--)
{
if(adj[v][i]==1 &&
state[i]==initial) push(i);
}
}
}/*End of DFS( )*/

void push(int v)
{
if(top == (MAX-1))
{
printf("\nStack Overflow\n");
return;
}
top=top+1;
stack[top] = v;
}/*End of push()*/

int pop()
{
int v;
if(top == -1)
{
p
r
} i
else n
t
{ f
(
"
\
} n
S
t
a
c
k
U
n
d
e
r
f
l
o
w
\
n
"
)
;
e
x
i
t
(
1
)
;

v
=
s
t
a
c
k
[
t
o
p
]
;
t ;
o r
p e
= t
t u
o r
p n
- v
1 ;
}/*End of pop()*/

int isEmpty_stack( )
{
if(top == -1)
return 1;
else
return 0;
}/*End if isEmpty_stack()*/

void create_graph()
{
int i,max_edges,origin,destin;

printf("\nEnter number of nodes : ");


scanf("%d",&n);
max_edges=n*(n-1);

for(i=1;i<=max_edges;i++)
{
printf("\nEnter edge %d( -1 -1 to quit ) : ",i);
scanf("%d %d",&origin,&destin);

if( (origin == -1) && (destin == -1) )


break;

if( origin >= n || destin >= n || origin<0 || destin<0)


{
p
r
} i
else n
t
{
f
(
} "
} \
} n
I
n
v
a
l
i
d
e
d
g
e
!
\
n
"
)
;
i
-
-
;

adj[origin][destin] = 1;
Output:

Result:
Thus the C program to implement DFS Algorithm for Connected Graph using a stack has
been executed and verified successfully.

You might also like