Lab Manual Data Structures Using JAVA-R1UC303B

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

LAB MANUAL

Data Structures using Java

School of Computer Science & Engineering

Computer Science & Engineering

2024-2025
SUBJECT Data Structure using Java PROGRAMME B.Tech CSE and
Specialization III Sem

SUBJECT CODE R1UC303B SEMESTER 3

DURATION OF
CREDITS 1 15 Weeks
SEMESTER
PREREQUISITE SESSION
C/C++/Java 2 Hrs per Week
SUBJECTS DURATION

Vision

"To be recognized globally as a premier School of Computing Science and Engineering for imparting
quality and value-based education within a multi-disciplinary and collaborative research-based
environment."

Mission
The mission of the school is to:

M1: Develop a strong foundation in fundamentals of computing science and engineering with
responsiveness towards emerging technologies.

M2: Establish state-of-the-art facilities and adopt education 4.0 practices to analyze, develop, test and
deploy sustainable ethical IT solutions by involving multiple stakeholders.

M3: Foster multidisciplinary collaborative research in association with academia and industry through
focused research groups, Centre of Excellence, and Industry Oriented R&D Labs.
PROGRAM EDUCATIONAL OBJECTIVES
The Graduates of Computer Science and Engineering shall:

PEO1: Graduates will possess the knowledge and skills to analyze, design, and implement efficient data
structures and algorithms using Java, preparing them for advanced studies or professional careers in
software development.

PEO2: Graduates will be proficient in identifying problems, formulating solutions, and implementing them
using data structures in Java, enabling them to address real-world challenges in diverse domains.

PEO3: Graduates will demonstrate the capability to stay current with technological advancements, adapt to new
tools and programming languages, and continuously improve their skills to remain competitive in the dynamic
field of software engineering.

PROGRAMME SPECIFIC OUTCOME (PSO):


The students of Computer Science and Engineering shall:

PSO1: Have the ability to work with emerging technologies in computing requisite to Industry 4.0.

PSO2: Demonstrate Engineering Practice learned through industry internship and research project
to solve live problems in various domains.
PROGRAMME OUTCOME (PO):
PO1 Computing Science knowledge: Apply the knowledge of mathematics, statistics, computing
science and information science fundamentals to the solution of complex computer application
problems.

PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
computing science problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and computer sciences.

PO3 Design/development of solutions: Design solutions for complex computing problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.

PO4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
computing science and IT tools including prediction and modeling to complex computing activities
with an understanding of the limitations.

PO6 IT specialist and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional computing science and information science practice.

PO7 Environment and sustainability: Understand the impact of the professional computing science
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the computing science practice.

PO9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the IT
analyst community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear
instructions.

PO11 Project management and finance: Demonstrate knowledge and understanding of the
computing science and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
List of Programs

Programs
1 Write a Program to implement addition and multiplication of two 2D arrays
2 Write a Program to implement Singly Linked List
3 Write a Program to implement stack using array.
4 Write a program to implement queue using array.
5 Write a program to implement circular queue using array.
6 Write a program to implement stack using linked list.
7 Write a program to implement queue using linked list.
8 Write a program to implement circular queue using linked list.
9 Write a program to implement binary search tree using linked list.
10 Write a program to implement Linear search and binary Search.
11 Write a program to implement Insertion Sorting.
12 Write a program to implement Bubble Sorting.
13 Write a program to convert Infix to Prefix and postfix representation of an
expression.
14 Write a program to implement BFS using array.
15 Write a program to implement DFS using linked list.

Value Added Programs:


1. Implementation of Client-Server model in Educational Enterprise.
2. Implementation of Client – Server Communication using RPC
3. Implementation of RSA Algorithm.

Course Outcomes

Upon successful completion of this course, students will be able to

CO1 Develop programs for functions like traversal, searching, and sorting over Arrays
and Linked Lists using iterative and recursive techniques.

CO2 Convert iterative programs using Arrays and Linked Lists into equivalent Recursive
versions and vice versa.
CO3 Implement Stack, Queue, and Binary Tree data structures in Java using Array and
Linked Structures.
CO4 Develop Java programs to solve computing problems using multiple data structures
(Stack, Queue, and Binary Tree).
CO-PO-PSO MAPPING:
CO/PO
Mapping

(S/M/W or 3/2/1 indicates strength of S/3-Strong, M/2-Medium, L/1-Low


correlation)
Programme Outcomes (POs) / Programme Specific Outcome (PSO)
CO’s
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2

CO1 1
1 1
CO2 1
CO3 1

CO4 2 2 2 2 1 1

Continuous Assessment Pattern

Rubrics for Lab (Work+ Record)

S. No. Rubrics - Parts Marks

1 Class Performance 5

2 Attendance 5

3 File 10

4 Viva 5

Total 25
Experiment 1

AIM: Write a Program to implement addition and multiplication of two 2D arrays

Objectives:

To understand and implement the addition and multiplication of two 2D arrays using Java.

Algorithm for matrix Addition:

Description: Here A is a two–dimensional array with M rows and N columns and B is a two–
dimensional array with X rows and Y columns. This algorithm adds these two arrays.
1. If (M≠ X) or (N≠ Y) Then
2. Print: Addition is not possible.
3. Exit [End of If]
4. Repeat For I = 1 to M
5. Repeat For J = 1 to N
6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop]
7. Exit

Explanation: First, we have to check whether the rows of array A are equal to the rows of array
B or the columns of array A are equal to the columns of array B. if they are not equal, then
addition is not possible and the algorithm exits. But if they are equal, then first for loop iterates
to the total number of rows i.e. M and the second for loop iterates to the total number of columns
i.e. N. In step 6, the element A[I][J] is added to the element B[I][J] and is stored in C[I][J] by
the statement: C[I][J] = A[I][J] + B[I][J].

Algorithm for matrix Multiplication:

Description: Here A is a two– dimensional array with M rows and N columns and B is a
two –dimensional array with X rows and Y columns. This algorithm multiplies these two
arrays.

1. If (M≠ Y) or (N≠ X) Then


2. Print: Multiplication is not possible.
3. Else
4. Repeat For I = 1 to N
5. Repeat For J = 1 to X
6. Set C[I][J] = 0
7. Repeat For K = 1 to Y
8. Set C[I][J] = C[I][J] + A[I][K] * B[K][J]
[End of Step 7 For Loop]
[End of Step 5 For Loop]
[End of Step 4 For Loop]
[End of If]
9. Exit

Explanation: First we check whether the rows of A are equal to columns of B or the columnsof
A are equal to rows of B. If they are not equal, then multiplication is not possible. But, ifthey are
equal, the first for loop iterates to total number of columns of A i.e. N and the secondfor loop
iterates to the total number of rows of B i.e. X. In step 6, all the elements of C are setto zero.
Then the third for loop iterates to total number of columns of B i.e. Y. In step 8, theelement
A[I][K] is multiplied with B[K][J] and added to C[I][J] and the result is assigned toC[I][J] by
the statement: C[I][J] = C[I][J] + A[I][K] * B[K][J].

Post-Experiment Questions:

Q1. For which of the following applications is an array NOT suitable:


a. Holding the scores on twelve midterms exams of a class.
b. Holding the name, social security number, age, and income of one individual.
c. Holding the temperature readings taken every hour throughout a day.
d. Holding the total sales a store made in each of twelve months.

Q2. How to pass a 2D array as a parameter in C?

Q3. Predict the output of the following program:


int main()
{ int i;
int arr[5] = {1};
for (i = 0; i < 5; i++)
printf("%d ", arr[i]);
return 0;
}

Q 4. How to modify the program to print Lower triangular and Upper triangular matrix of an
array?
Experiment 2

AIM: Write a Program to implement the Singly Linked List

Objective:
To understand and implement a singly linked list in Java and perform various operations
such as insertion, deletion, and traversal.

Algorithm:

Initialization:
Define Node Class:
• Each node should have two attributes: data (to store the value) and
next (to store the reference to the next node).
Create Linked List Class:
• This class should have a head attribute that points to the first node
of the linked list.
• Insertion Operations:

Insert at the Beginning:


Step 1: Create a new node.
Step 2: Set the new node's next to the current head.
Step 3: Update the head to the new node.

Insert at the End:


Step 1: Create a new node.
Step 2: Traverse to the last node of the linked list.
Step 3: Set the last node's next to the new node.

Insert at a Given Position:


Step 1: Create a new node.
Step 2: Traverse to the node just before the desired position.
Step 3: Set the new node's next to the current node's next.
Step 4: Set the current node's next to the new node.

Deletion Operations:
Delete from the Beginning:
Step 1: Check if the linked list is empty.
Step 2: Update the head to the next node of the current head.

Delete from the End:


Step 1: Check if the linked list is empty.
Step 2: Traverse to the second last node of the linked list.
Step 3: Set the second last node's next to null.

Delete from a Given Position:


Step 1: Check if the linked list is empty.
Step 2: Traverse to the node just before the desired position.
Step 3: Update the next of the current node to the next of the node to be deleted.

Traversal Operation:
Traverse the Linked List:
Step 1: Start from the head.
Step 2: Print the data of each node.
Step 3: Move to the next node using the next reference.
Step 4: Repeat steps 2 and 3 until the end of the linked list is reached.

Example Input and Output:


Example 1: Insertion
Input: Insert 10 at the beginning, 20 at the end, 15 at position 2
Output: Linked List: 10 -> 15 -> 20
Example 2: Deletion
Input: Delete from the beginning, delete from the end, delete from position 2
Output: After deleting from the beginning: 15 -> 20, After deleting from the end: 15, After
deleting from position 2: (list is empty)
Example 3: Traversal
Input: Linked List: 10 -> 15 -> 20
Output: 10 15 20

Post-Experiment Questions:

1. Insert elements 5, 10, 15, 20, 25 into the linked list in the given order and then
print the linked list.
a. Write a function to search for an element in the linked list. If the element
is found, print its position; otherwise, print "Element not found."
b. Write a function to count the number of nodes in the linked list and print
the count.
2. Write a program to merge two sorted linked lists into a single sorted linked list
and print the merged list.
Experiment 3

AIM: Write a Program to implement stack using array.

Objective:
1. Understand the stack data structure.
2. Learn how to implement a stack using an array in Java.
3. Perform basic stack operations: push, pop, peek, isEmpty, and isFull.

Algorithms:

Procedures to support stack functions −


peek() function
• Before returning the top element from the stack, we check if the stack is empty.
• If the stack is empty (top == -1), we simply print “Stack is empty”.Otherwise, we return the
element stored at index = top .

isfull() function
• Check for the value of top in stack.
• If (top == capacity-1), then the stack is full so return true .
• Otherwise, the stack is not full so return false.

isempty() function
• Check for the value of top in stack.
• If (top == -1) , then the stack is empty so return true .
• Otherwise, the stack is not empty so return false .

Implementation of isempty() function in C programming language is slightly different. We initialize top at


-1, as the index in array starts from 0. So, we check if the top is below zero or -1 to determine if the stack
is empty.

Push operation can be derived as follows –


• Before pushing the element to the stack, we check if the stack is full .
• If the stack is full (top == capacity-1) , then Stack Overflows and we cannot insert the element
to the stack.
• Otherwise, we increment the value of top by 1 (top = top + 1) and the new value is inserted at
top position .
• The elements can be pushed into the stack till we reach the capacity of the stack.

Pop operation can be derived as follows −


• Before popping the element from the stack, we check if the stack is empty .
• If the stack is empty (top == -1), then Stack Underflows and we cannot remove any element
from the stack.
• Otherwise, we store the value at top, decrement the value of top by 1 (top = top – 1) and
return the stored top value.
Example Input and Output:

Input:
push 10, 20, 30
pop 30
Output:
Top element is : 20
Elements present in stack : 20 10

Post-Experiment Questions:
1. How does the stack handle overflow?
a. What happens if you try to push an element onto a full stack?
2. How does the stack handle underflow?
a. What happens if you try to pop an element from an empty stack?
3. Write a program to reverse a string
a. Example: Input: "hello" Output: "olleh".
4. Solve the Tower of Hanoi problem using stacks.
Experiment 4

AIM: Write a Program to implement queue using array.

Objective:
To understand and implement the basic operations of a queue using an array in Java.

Algorithms:
Procedures to support queue functions –
enqueue():
1. Check the queue is full or not
2. If full, print overflow and exit
3. If queue is not full, increment tail and add the element

dequeue():
1. Check queue is empty or not
2. if empty, print underflow and exit
3. if not empty, print element at the head and increment head

isFullQueue():
1. To check if the queue is full, compare the number of elements in the queue (count) with
MAX_SIZE.
2. If count equals MAX_SIZE, the queue is full.

isEmptyQueue():
1. If number of elements in the queue (count) is equal to 0, then the queue is empty.
2. Otherwise, the queue is not empty.

Example Input and Output:

Input:
enqueue 10, 20, 30, 40
dequeue 10
Output:
Front item is 20
Rear item is 40

Post-Experiment Questions:

1. Find the maximum or minimum element in every subarray of size k in an array.


a. Example: Given an array [1, 3, 1, 2, 0, 5] and k = 3, the maximums are [3,
3, 2, 5].
2. Write a C program to reverse the elements of a queue.
3. Implement Queue using Two Stacks
Experiment 5

AIM: Write a Program to implement circular queue using array.

Objective:

To understand and implement a circular queue using an array in Java, covering basic operations such
as enqueue, dequeue, checking if the queue is full or empty, and peeking at the front and rear
elements.

Algorithm:

IsFull Implementation
1. Check if the front index is equal to the rear index.
2. If true, the queue is empty; return true.
3. Otherwise, return false.

IsEmpty Implementation
1. Check if the (rear + 1) % MAX_SIZE is equal to the front index.
2. If true, the queue is full; return true.
3. Otherwise, return false.

Enqueue Implementation
1. Check if the queue is full using the isFull function.
2. If the queue is full, print “Queue Overflow” and return.
3. Otherwise, increment the rear index using (rear + 1) % MAX_SIZE.
4. Insert the new element at the rear index.

Dequeue Implementation
1. Check if the queue is empty using the isEmpty function.
2. If the queue is empty, print “Queue Underflow” and return.
3. Otherwise, increment the front index using (front + 1) % MAX_SIZE.

Peek Implementation
1. Check if the queue is empty using the isEmpty function.
2. If the queue is empty, print “Queue is Empty” and return -1.
3. Otherwise, return the element at (front + 1) % MAX_SIZE.

Example Input and Output:

Input:
Insert 10, 20, 30
Delete 30
Insert 50

Output:
Queue elements: 10 20 30
Dequeued element: 10
Queue elements: 20 30 50

Post-Experiment Questions:

1. Design and implement a circular buffer for handling streaming data. Ensure that the buffer
correctly overwrites old data when new data arrives.

2. Simulate a printer queue using a circular queue. Implement functionalities for adding print
jobs, processing print jobs, and handling cases where the queue is full.
Experiment 6

AIM: Write a Program to implement stack using linked list

Objective:
To implement a stack data structure using a linked list and perform operations such as
push, pop, and peek. This will help understand the stack's LIFO (Last-In-First-Out)
nature and how it can be managed using linked lists.

Algorithm of Push Operation


Procedure:
1. Create a new node.
2. Set the data of the new node to the value being pushed onto the stack.
3. Point the next of the new node to the current top of the stack.
4. Update the top of the stack to the new node.
Steps:
1. Allocate memory for the new node.
2. Assign the value to the data field of the new node.
3. Set the next field of the new node to point to the current top.
4. Update the top pointer to the new node.

Algorithm of Pop Operation


Procedure:
1. Check if the stack is empty.
2. If not empty, retrieve the data from the top node.
3. Update the top of the stack to point to the next node.
4. Deallocate memory for the removed node.
Steps:
1. Verify that the stack is not empty.
2. Store the data of the top node.
3. Update the top pointer to point to the next node.
4. Free the memory allocated for the old top node.
5. Return the stored data.

Algorithm of Peek Operation


Procedure:
1. Check if the stack is empty.
2. If not empty, retrieve the data from the top node without removing it.
Steps:
1. Verify that the stack is not empty.
2. Return the data of the top node.
Algorithm of IsEmpty Operation
Procedure:
1. Check if the top of the stack is NULL.
2. Return true if the top is NULL, otherwise return false.
Steps:
1. If the top pointer is NULL, the stack is empty.
2. Return the result of the check.

Example Input and Output:


Input:
Push Operations: Push 10, 20, and 30 onto the stack.
Peek Operation: Retrieve the top element (should be 30).
Pop Operation: Remove the top element (should be 30).
Peek Operation After Pop: Retrieve the new top element (should be 20).
Output:
Top element is 30
Popped element is 30
Top element after pop is 20

Post-Experiment Questions:

1. Extend your stack implementation to handle multiple data types (e.g., integers, floats, strings).
2. Design and implement a calculator that uses a stack to evaluate arithmetic expressions.
3. Modify your stack implementation to maintain and provide the current size of the stack. Add a
size function to return the number of elements in the stack.
Experiment 7

AIM: Write a Program to implement queue using linked list

Objective:

To implement a queue using a linked list and understand the operations involved: enqueue,
dequeue, and checking if the queue is empty or not.

Algorithm:

Initialization

Steps:
1. Define a Node class to represent each element in the queue. Each node should
contain the data and a reference to the next node.
2. Create a Queue class that includes references to the front and rear nodes of the
queue.
3. Initialize the front and rear pointers to null when the queue is empty.

Enqueue Operation

Steps:
1. Create a new node with the given data.
2. If the queue is empty (i.e., front is null), set both the front and rear pointers to the
new node.
3. If the queue is not empty, link the new node to the end of the queue by setting the
next pointer of the rear node to the new node.
4. Update the rear pointer to the new node.

Dequeue Operation

Steps:
1. If the queue is empty (i.e., front is null), indicate that the queue is empty and no
element can be dequeued.
2. If the queue is not empty, store the data of the front node to return later.
3. Move the front pointer to the next node in the queue.
4. If the front becomes null (i.e., the queue becomes empty), also set the rear pointer
to null.
5. Return the stored data.

isEmpty Operation

Steps:
1. Return true if both the front and rear pointers are null.
2. Otherwise, return false.

Peek Operation

Steps:
1. If the queue is empty (i.e., front is null), indicate that the queue is empty and there
is no element to peek.
2. If the queue is not empty, return the data of the front node.
Example Input and Output:

Input:
Enqueue 10, 20, 30
Dequeue one element

Output:
Dequeued element: 10
Queue contains: 20 30

Post-Experiment Questions:
1. Implement a Queue using Linked List. A Query Q is of 2 Types
(i) 1 x (a query of this type means pushing 'x' into the queue)
(ii) 2 (a query of this type means to pop an element from the queue and print the poped
element)
Input:
Q=5
Queries = 1 2 1 3 2 1 4 2
Output: 2 3
Explanation: In the first test case 1 2 the queue will be {2}. 1 3 the queue will be {2
3}. 2 popped element will be 2 the queue will be {3}. 1 4 the queue will be {3 4}. 2
popped element will be 3.
Experiment 8

AIM: Write a Program to implement a circular queue using linked list

Objectives:

To understand and implement a circular queue using a linked list in Java.

Algorithm:

Initialization

Define Node Class


1. Create a class called Node with two attributes: data and next.
2. The data attribute will store the value of the node, and the next attribute will point to the next
node
in the queue.

Define CircularQueue Class


1. Create a class called CircularQueue with two attributes: rear and size.
2. The rear attribute will point to the last node in the queue, and the size attribute will keep track
of the number of elements in the queue.

Enqueue Operation

Create a New Node


Create a new node with the given data.

Insert the New Node


1. If the queue is empty (i.e., rear is null), set the new node's next to point to itself and set rear to
the new node.
2. If the queue is not empty, set the new node's next to point to rear.next, then update rear.next to
point to the new node, and finally set rear to the new node.

Increment the Size


1. Increase the size of the queue by one.

Dequeue Operation

Check if the Queue is Empty


1. If rear is null, the queue is empty, and the operation cannot be performed.

Remove the Front Node


1. If there is only one node in the queue, set rear to null.
2. If there are multiple nodes, set the front node to rear.next, store the value of the front
node, update rear.next to point to front.next, and decrease the size of the queue by one.

Return the Value


1. Return the value of the removed node.

Peek Operation

Check if the Queue is Empty


1. If rear is null, the queue is empty, and the operation cannot be performed.

Return the Front Value


1. Return the value of the node pointed to by rear.next.
IsEmpty Operation

Check if the Queue is Empty


1. If the rear is null, return true; otherwise, return false.

Example Input and Output:

Input:
Enqueue 10, 20, 30
Dequeue one element

Output:
Dequeued element: 10
Queue contains: 20 30

Post-Experiment Questions:

1. Circular Buffer for Streaming Data

Problem: Design a circular buffer to handle streaming data. Ensure that when the buffer is
full, new data overwrites the oldest data.

Example: Buffer size 3; data 1, 2, 3 added; adding 4 should overwrite 1.


Experiment 9

AIM: Write a Program to implement a binary search tree using linked list
Objective:

To understand and implement a Binary Search Tree (BST) using a linked list in Java, and perform various
operations such as insertion, deletion, and traversal.

Algorithm:

BST Node Structure

Details: Each node contains:


• An integer value (or data).
• References to the left and right child nodes.

Inserting a Node into the BST

Procedure:
1. Start at the root of the BST.
2. Compare the value to be inserted with the value of the current node.
3. If the value is less than the current node's value, move to the left child.
4. If the value is greater than the current node's value, move to the right child.
5. Repeat steps 2-4 until reaching a null reference.
6. Insert the new node at the null position.

Deleting a Node from the BST

Procedure:
1. Start at the root of the BST.
2. Search for the node to be deleted.
3. If the node has no children, simply remove it.
4. If the node has one child, replace the node with its child.
5. If the node has two children:
6. Find the inorder successor (the smallest node in the right subtree).
7. Replace the node's value with the inorder successor's value.
8. Delete the inorder successor.

Inorder Traversal of the BST

Procedure:
1. Start at the root node.
2. Recursively traverse the left subtree.
3. Visit the current node.
4. Recursively traverse the right subtree.

Preorder Traversal of the BST

Procedure:
1. Start at the root node.
2. Visit the current node.
3. Recursively traverse the left subtree.
4. Recursively traverse the right subtree.

Postorder Traversal of the BST

Procedure:
1. Start at the root node.
2. Recursively traverse the left subtree.
3. Recursively traverse the right subtree.
4. Visit the current node.

Example Input and Output:

Input:
1. Insert the values 50, 30, 70, 20, 40, 60, 80 into an empty BST.
2. Delete the value 70 from the BST.
3. Perform inorder, preorder and postorder traversal on the BST.

Output:
1. Inorder Traversal: 20, 30, 40, 50, 60, 80
2. Preorder Traversal: 50, 30, 20, 40, 80, 60
3. Postorder Traversal: 20, 40, 30, 60, 80, 50

Post-Experiment Questions:
1. Write a Java program to search for a given value in a BST.
2. Write a Java program to find the minimum and maximum values in a BST.
3. Write a Java program to check if a given binary tree is a valid BST.
Experiment 10

AIM: Write a Program to implement a BFS using an array

Objective:

To implement the Breadth-First Search (BFS) algorithm using arrays in Java.

Algorithm:

Initialize the Graph


• Represent the graph using an adjacency matrix or an adjacency list.
• An adjacency matrix is a 2D array where graph[i][j] = 1 indicates an edge between
nodes i and j.
• An adjacency list is an array of lists where each list contains the neighbors of a node.

Initialize the BFS Data Structures


• Queue: Use an array-based queue to keep track of nodes to be visited.
• Visited Array: Maintain an array to track visited nodes, initialized to false for all nodes.

Enqueue the Starting Node


1. Select the starting node (source).
2. Mark the starting node as visited.
3. Enqueue the starting node into the queue.

BFS Traversal
1. While the queue is not empty:
2. Dequeue a node from the front of the queue.
3. Process the dequeued node (e.g., print it or record it).
4. For each unvisited neighbor of the dequeued node:
5. Mark the neighbor as visited.
6. Enqueue the neighbor.

End of BFS
The BFS ends when the queue becomes empty, indicating that all reachable nodes
have been visited.

Example Input and Output

Input:

Consider the following graph represented as an adjacency matrix:

Output

The BFS traversal order starting from node 0 is: 0 -> 1 -> 2 -> 3 -> 4
Post-Experiment Questions:

1. Given a graph, implement BFS to find the shortest path from a starting node to all
other nodes.

2. Use BFS to find and print all connected components of an undirected graph.
Experiment 11

AIM: Write a Program to implement a DFS using linked list

Objective:

To implement the Breadth-First Search (DFS) algorithm using linked list in Java.

Algorithm:

Create Graph Structure

Define a class to represent a graph node.


• Each node should store a list of adjacent nodes (neighbors).

Define the Graph class.


• Use a linked list to store adjacent nodes.
• Include methods to add nodes and edges to the graph.

Initialize Graph

Create an instance of the Graph class.


• Initialize the adjacency list for each node.

Add edges to the graph.


• Populate the adjacency list with edges representing connections
between nodes.

Implement DFS Algorithm

Define a method to perform DFS traversal.


1. Use a boolean array to keep track of visited nodes.
2. Use a helper function to recursively visit nodes.

In the helper function:


1. Mark the current node as visited.
2. Print or store the current node.
3. Recur for all the vertices adjacent to this vertex.

Perform DFS Traversal

Call the DFS method on the Graph instance.


1. Pass the starting node of the traversal.
2. Ensure all nodes are reachable by iterating through each node and checking
if it has been visited.

Example Input and Output:


Input Graph: DFS Traversal Starting from Node 2
0 -> 1 -> 2
1 -> 2
2 -> 0 -> 3
3 -> 3

Output: 2 0 1 3
Post-Experiment Questions:

1. Modify the DFS implementation to detect if there's a cycle in an undirected grraph.


2. Find the sum of weights along the path of traversal using DFS
Experiment 12

AIM: Write a Program to implement Linear search and binary Search.

Objective:

To understand and implement linear search and binary search algorithms in Java.

Algorithm:

1. Linear Search

Define the Problem:


• Given an array of integers and a target value, determine if the target value
exists in the array.
• Initialize Variables:
• Input array of integers.
• Target value to be searched.

Linear Search Algorithm:


1. Start from the first element of the array.
2. Compare the current element with the target value.
3. If the current element matches the target value, return its index.
4. If the current element does not match, move to the next element.
5. Repeat steps until the end of the array.
6. If the target value is not found, return an indicator (e.g., -1).

Output:
1. Index of the target value if found.
2. Indicator if not found (e.g., -1).

2. Binary Search

Define the Problem:


• Given a sorted array of integers and a target value, determine if the target value exists in the
array.

Initialize Variables:
• Input sorted array of integers.
• Target value to be searched.
• Two pointers: low and high.

Binary Search Algorithm:


1. Set low to the first index of the array.
2. Set high to the last index of the array.
3. While low is less than or equal to high:
4. Calculate the middle index mid as (low + high) / 2.
5. Compare the middle element with the target value.
6. If the middle element matches the target value, return its index.
7. If the middle element is greater than the target value, set high to mid - 1.
8. If the middle element is less than the target value, set low to mid + 1.
9. If the target value is not found, return an indicator (e.g., -1).

Output:
Index of the target value if found.
Indicator if not found (e.g., -1).

Example Input and Output:


Input 1: Array: [10, 20, 30, 40, 50]
Target value: 40

Output1:
Index: 3

Input 2:
Array: [5, 15, 25, 35, 45]
Target value: 100

Output 2:
Index: -1 (indicating the target is not found)

Post-Experiment Questions:

1. Implement a linear search to find the index of the value 7 in the array [1, 3, 5, 7, 9,
11].

2. Given a sorted array of positive integers (elements may be repeated) and a


number x. The task is to find the first and last occurrence of x in the given array.
[Given, N= length of Array]

Input 1:
arr[] = [1, 10, 20, 20, 40]
x = 20
Output 1: 2 3

Input 2: arr[] = [10, 20, 30]


x = 15
Output 2: -1 -1

Input 3: arr[] = [15, 15, 15]


x = 15
Output 3: 0 2
Experiment 13

AIM: Write a Program to implement Insertion Sort.

Objective:

The objective of this lab is to understand and implement the Insertion Sort algorithm in Java. By the end
of this lab, you should be able to:

• Understand the step-by-step procedure of Insertion Sort.


• Apply Insertion Sort to sort an array.

Algorithm:
1. We have to start with second element of the array as first element in the
array is assumed to be sorted.
2. Compare second element with the first element and check if the second
element is smaller then swap them.
3. Move to the third element and compare it with the second element, then the
first element and swap as necessary to put it in the correct position among the first
three elements.
4. Continue this process, comparing each element with the ones before it and
swapping as needed to place it in the correct position among the sorted elements.
5. Repeat until the entire array is sorted.

Example Input and Output:

Input: [5, 2, 9, 1, 5, 6]

Sorting Steps:
• Initial Array: [5, 2, 9, 1, 5, 6]
• Take 2, compare with 5, and shift 5 to the right: [2, 5, 9, 1, 5, 6]
• Take 9, compare with 5 and 2, no shift needed: [2, 5, 9, 1, 5, 6]
• Take 1, compare with 9, 5, and 2, shift all to the right: [1, 2, 5, 9, 5, 6]
• Take 5, compare with 9, and shift 9 to the right: [1, 2, 5, 5, 9, 6]
• Take 6, compare with 9, and shift 9 to the right: [1, 2, 5, 5, 6, 9]

Output: [1, 2, 5, 5, 6, 9]

Post-Experiment Questions:

1. Sort a Reverse Sorted Array 9, 8, 7, 6, 5, 4, 3, 2, 1

2. Sort an Array of Strings "banana", "apple", "orange", "grape", "cherry"


Experiment 14

AIM: Write a Program to implement bubble Sort.

Objective:

The objective of this lab is to understand and implement the bubble Sort algorithm in Java. By the end of
this lab, you should be able to:

• Understand the step-by-step procedure of bubble Sort.


• Apply bubble Sort to sort an array.

Algorithm:

Understand Bubble Sort Algorithm:

• Bubble Sort is a simple sorting algorithm that repeatedly steps through the list,
compares adjacent elements, and swaps them if they are in the wrong order. The pass
through the list is repeated until the list is sorted.

• Each iteration of the outer loop moves the next largest element to its correct position.

Initialize the Array:

1. Define an array of integers that you want to sort.

2. For example, let's take an array of integers: [5, 3, 8, 4, 2].

Outer Loop:

1. Start an outer loop that runs from the first element to the last element of the array.
This loop represents each pass through the array.

2. The loop counter, i, will run from 0 to n-1 where n is the length of the array.

Inner Loop:

1. Within the outer loop, start an inner loop that runs from the first element to n-i-1.

2. The inner loop counter, j, will run from 0 to n-i-2. This ensures that each pass
compares the elements correctly without re-evaluating the already sorted elements.

Compare and Swap:

1. Within the inner loop, compare the current element (array[j]) with the next element
(array[j+1]).

2. If array[j] is greater than array[j+1], swap the two elements.

Repeat:

1. Repeat the inner loop until the end of the array is reached.

2. Repeat the outer loop until all elements are sorted.

End of Sorting:

• Once the outer loop finishes, the array is sorted.

Example Input and Output:


Input: [3, -2, -1, 0, 2, 1]
Output: [-2, -1, 0, 1, 2, 3]

Post-Experiment Questions:

Sort an Array of Characters:


Input: ['b', 'a', 'e', 'd', 'c']
Experiment 15

AIM: Write a Program to convert Infix to Prefix and postfix representation of an expression.

Objective:

To write a Java program that converts infix expressions to both prefix and postfix representations.

Algorithm:

1. Converting Infix to Postfix


Initialize an empty stack for operators and an empty list for the output.

Scan the infix expression from left to right:


1. If the scanned character is an operand, append it to the output list.
2. If the scanned character is an opening parenthesis (, push it onto the stack.
3. If the scanned character is a closing parenthesis ), pop from the stack and
append to the output list until an opening parenthesis ( is encountered. Discard
the pair of parentheses.

If the scanned character is an operator (+, -, *, /, ^):


1. While there is an operator at the top of the stack with greater precedence or
equal precedence (if the scanned operator is left-associative), pop from the
stack and append to the output list.
2. Push the scanned operator onto the stack.

Pop all the remaining operators from the stack and append to the output list.

2. Converting Infix to Prefix

Reverse the infix expression:


• Reverse the order of the characters.
• Swap opening and closing parentheses.

Convert the reversed infix expression to postfix using the above steps.
• Reverse the postfix expression obtained in step 2 to get the prefix
expression.

Example Input and Output:

Example 1: Converting Infix to Postfix


Input: A + B * C
Output: A B C * +
Example 2: Converting Infix to Prefix
Input: (A - B/C) * (A/K-L)
Output: * - A / B C - / A K L

Post-Experiment Questions:
Problem 1: Convert Infix to Postfix
Input: A * (B + C) / D
Expected Output: A B C + * D /

Problem 2: Convert Infix to Prefix


Input: A + B * (C ^ D - E)
Expected Output: + A * B - ^ C D E

Problem 3: Convert Prefix to Postfix


Input: *+AB-CD
Expected Output: AB+CD-*

You might also like