0% found this document useful (0 votes)
15 views105 pages

DS Lab Manual

Uploaded by

vrt.kolluru
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)
15 views105 pages

DS Lab Manual

Uploaded by

vrt.kolluru
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/ 105

PROGRAM CORE

Course Code Course Title L T P S C


22CS102003 DATA STRUCTURES 3 - 2 - 4
Pre-Requisite -
Anti-Requisite -
Co-Requisite -

COURSE DESCRIPTION: This course provides an overview of data structure concepts, arrays,
stack, queues, trees, and graphs. Discussion of various implementations of these data objects,
programming styles, and run-time representations.

COURSE OUTCOMES: After successful completion of the course, students will be able to:
CO1. Understand the concept of Dynamic memory management, data types, algorithms, Big
O notation.
CO2. Understand basic data structures such as arrays, linked lists, stacks and queues.
CO3. Solve problem involving graphs, trees and heaps.
CO4. Apply Algorithm for solving problems like sorting, searching, insertion and deletion of
data.

CO-PO-PSO Mapping Table:

Program Specific
Course Program Outcomes
Outcomes
Outcome P
s O PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 PSO4
1
CO1 3 2 - - - - - - - - - - 3 - - -
CO2 3 2 - - - - - - - - - - 3 - - -
CO3 3 3 3 - - - - - - - - - 3 - - -
CO4 3 3 3 2 - - - - - - - - 3 - - -
Course
Correla
tion 3 3 3 2 - - - - - - - - 3 - - -
Mappin
g
Correlation Levels: 3: High; 2: Medium; 1: Low
COURSE CONTENT
MODULE 1 INTRODUCTION TO DATA STRUCTURES & STACK, QUEUE (10 Periods)
Introduction: Introduction to Data Structures, Basic Concepts and Notations, Abstract Data Types,
Analysis and Efficiency of Algorithms, Time and Space Complexity.
Stack, Queue: Stack, Stack operations, Implementation using arrays, applications of stack, Queue,
Queue operations, Implementation using arrays, various Queue Structures, applications of queue.

MODULE 2 LINKED LISTS (8 Periods)


Linked lists: Single linked list, double linked list, circular linked list, operations on linked lists,
Applications of Linked List. Implementation of stack using Pointers, Implementation of Queue using
Pointers.

MODULE 3 SEARCHING, SORTING & HASH TABLES (8 Periods)


Searching Techniques: Linear Search, Binary Search and Fibonacci Search.
Sorting Techniques: Selection Sort, Insertion sort, Bubble sort, Merge Sort, Quick Sort, Heap
sort, Radix Sort.
Hash Tables: Hash Functions, Collision Handling Schemes, Applications.

MODULE 4 TREES (10 Periods)


Trees: Vocabulary and Definitions, Binary Tree, Implementation, Binary Tree Traversal, Binary
Search Tree, Implementation, Balanced Search Trees: AVL Trees, Implementation, Splay Trees,
Red-Black Trees.

MODULE 5 GRAPH THEORY (09 Periods)


GraphTheory: Graphs Terminology, Graph ADT, Data Structures for Graphs –Adjacency Matrix
Structure, Graph Traversals, Shortest Paths, Minimum Spanning Trees- Prims’ Algorithm, Kruskal’s
Algorithm, Dijkstra's Algorithm, Floyd-Warshall Algorithm
Total Periods: 45
Experiential Learning:
1. Demonstrate recursive algorithms with examples.
2. Develop a program to perform operations of a Stack and Queue using arrays.
3. Implement and perform different operations on Single, Double and Circular Linked Lists.
4. Develop a program to perform operations of Stack and Queue using Linked Lists
5. Develop programs to implement Stack applications.
6. Implement Circular Queues.
7. Implement various Searching techniques.
8. Develop programs for different Sorting techniques
9. Develop a program to represent a Tree data structure.
10. Develop a program to demonstrate operations on Binary Search Tree.
11. Demonstrate Graph Traversal Techniques.
12. Develop a program to find Minimum cost Spanning tree.
References:

Text Books:
1. Mark Allen Weiss, Data Structures and Algorithm Analysis in C, Pearson, Second Edition,
2002.
2. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein Introduction to
Algorithms, PHI, Third Edition,2010.
3. Narasimha Karumanchi, Data Structures and Algorithms Made Easy, Career Monk
Publications,2020.

Reference Books:

1. Horowitz, Sahani, Anderson Freed, Fundamental of Data Structures in C, Universities


Press, Second Edition, 2008.
2. Debasis Samantha, Classic Data Structures, PHI, Second Edition, 2009.

Video Resources:
1. https://www.youtube.com/watch?v=zWg7U0OEAoE&list=PLBF3763AF2E1C572F
2. https://www.youtube.com/watch?v=S47aSEqm_0I&list=PLD9781AC5EBC9FA16
3. https://www.youtube.com/watch?v=9MmC_uGjBsM&list=PLyqSpQzTE6M_Fu6l8irVwXkUyC9Gwqr6

WEB RESOURCES:
1. https://www.tutorialspoint.com/what-is-advanced-java
2. https://www.udemy.com/course/advanced-java-programming/
3. https://www.geeksforgeeks.org/what-is-advanced-java/
4. https://cloudacademy.com/learning-paths/advanced-java-programming-518/
Experien al Learning
DATA STRUCTURES (22CS102003)

WEEK 1
AIM: To demonstrate recursive algorithms with examples.
SOURCE CODE:
a. Factorial:
public class Factorial {
public sta c int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}

public sta c void main(String[] args) {


int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}
OUTPUT:
Factorial of 5 is: 120
b. Fibonacci Sequence:
public class Fibonacci {
public sta c int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}

public sta c void main(String[] args) {


int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
OUTPUT:
0 1 1 2 3 5 8 13 21 34
WEEK 2
AIM: To develop a program to perform opera ons of a Stack and Queue using
arrays.
SOURCE CODE:
import java.u l.Scanner;

// Stack class implementa on


class Stack {
private int size;
private int[] stackArray;
private int top;

public Stack(int size) {


this.size = size;
this.stackArray = new int[size];
this.top = -1;
}

public boolean isEmpty() {


return (top == -1);
}

public boolean isFull() {


return (top == size - 1);
}
public void push(int value) {
if (!isFull()) {
stackArray[++top] = value;
System.out.println("Pushed " + value + " into the stack.");
} else {
System.out.println("Stack is full. Cannot push " + value);
}
}

public int pop() {


if (!isEmpty()) {
return stackArray[top--];
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1;
}
}

public int peek() {


if (!isEmpty()) {
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1;
}
}
}

// Queue class implementa on


class Queue {
private int size;
private int[] queueArray;
private int front;
private int rear;
private int nItems;

public Queue(int size) {


this.size = size;
this.queueArray = new int[size];
this.front = 0;
this.rear = -1;
this.nItems = 0;
}

public boolean isEmpty() {


return (nItems == 0);
}

public boolean isFull() {


return (nItems == size);
}

public void insert(int value) {


if (!isFull()) {
if (rear == size - 1) {
rear = -1;
}
queueArray[++rear] = value;
nItems++;
System.out.println("Inserted " + value + " into the queue.");
} else {
System.out.println("Queue is full. Cannot insert " + value);
}
}

public int remove() {


if (!isEmpty()) {
int temp = queueArray[front++];
if (front == size) {
front = 0;
}
nItems--;
return temp;
} else {
System.out.println("Queue is empty. Cannot remove.");
return -1;
}
}

public int peekFront() {


if (!isEmpty()) {
return queueArray[front];
} else {
System.out.println("Queue is empty. Cannot peek.");
return -1;
}
}
}

// Main class to test Stack and Queue


public class Main {
public sta c void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Stack opera ons


System.out.println("Enter the size of the stack:");
int stackSize = scanner.nextInt();
Stack stack = new Stack(stackSize);

System.out.println("Stack opera ons:");


while (true) {
System.out.println("Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value to push:");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
System.out.println("Popped element: " + stack.pop());
break;
case 3:
System.out.println("Top element: " + stack.peek());
break;
case 4:
System.out.println("Exi ng stack opera ons.");
break;
default:
System.out.println("Invalid choice. Try again.");
}
if (choice == 4) break;
}
// Queue opera ons
System.out.println("Enter the size of the queue:");
int queueSize = scanner.nextInt();
Queue queue = new Queue(queueSize);

System.out.println("Queue opera ons:");


while (true) {
System.out.println("Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-
Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value to insert:");
int valueToInsert = scanner.nextInt();
queue.insert(valueToInsert);
break;
case 2:
System.out.println("Removed element: " + queue.remove());
break;
case 3:
System.out.println("Front element: " + queue.peekFront());
break;
case 4:
System.out.println("Exi ng queue opera ons.");
break;
default:
System.out.println("Invalid choice. Try again.");
}
if (choice == 4) break;
}
scanner.close();
}
}
OUTPUT:
Enter the size of the stack:
3
Stack opera ons:
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
10
Pushed 10 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
20
Pushed 20 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
30
Pushed 30 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
40
Stack is full. Cannot push 40
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
3
Top element: 30
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Popped element: 30
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Popped element: 20
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Popped element: 10
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Stack is empty. Cannot pop.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
4
Exi ng stack opera ons.
Enter the size of the queue:
3
Queue opera ons:
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
1
Enter value to insert:
5
Inserted 5 into the queue.
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
1
Enter value to insert:
10
Inserted 10 into the queue.
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
1
Enter value to insert:
15
Inserted 15 into the queue.
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
1
Queue is full. Cannot insert 20
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
3
Front element: 5
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
2
Removed element: 5
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
2
Removed element: 10
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
2
Removed element: 15
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
2
Queue is empty. Cannot remove.
Choose an opera on: 1-Insert, 2-Remove, 3-Peek, 4-Exit
4
Exi ng queue opera ons.
WEEK 3
AIM: To implement and perform different opera ons on Single, Double and
Circular Linked Lists.
SOURCE CODE:
SingleLinkedList.java:
class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}

class SingleLinkedList {
Node head;

void insertAtHead(int data) {


Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}

void append(int data) {


Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}

void insertA er(Node prevNode, int data) {


if (prevNode == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node newNode = new Node(data);
newNode.next = prevNode.next;
prevNode.next = newNode;
}

void delete(int key) {


Node current = head;
Node previous = null;
if (current != null && current.data == key) {
head = current.next;
return;
}
while (current != null && current.data != key) {
previous = current;
current = current.next;
}
if (current == null) return;
previous.next = current.next;
}

void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
DoubleLinkedList.java:
class DoubleNode {
int data;
DoubleNode next;
DoubleNode prev;
DoubleNode(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}

class DoubleLinkedList {
DoubleNode head;

void insertAtHead(int data) {


DoubleNode newNode = new DoubleNode(data);
newNode.next = head;
if (head != null) {
head.prev = newNode;
}
head = newNode;
}

void append(int data) {


DoubleNode newNode = new DoubleNode(data);
if (head == null) {
head = newNode;
return;
}
DoubleNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.prev = current;
}

void insertA er(DoubleNode prevNode, int data) {


if (prevNode == null) {
System.out.println("The given previous node cannot be null");
return;
}
DoubleNode newNode = new DoubleNode(data);
newNode.next = prevNode.next;
if (prevNode.next != null) {
prevNode.next.prev = newNode;
}
prevNode.next = newNode;
newNode.prev = prevNode;
}

void delete(int key) {


DoubleNode current = head;
if (current != null && current.data == key) {
head = current.next;
if (head != null) {
head.prev = null;
}
return;
}
while (current != null && current.data != key) {
current = current.next;
}
if (current == null) return;
if (current.next != null) {
current.next.prev = current.prev;
}
if (current.prev != null) {
current.prev.next = current.next;
}
}

void printList() {
DoubleNode current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
CircularLinkedList.java:
class CircularNode {
int data;
CircularNode next;

CircularNode(int data) {
this.data = data;
this.next = null;
}
}

class CircularLinkedList {
CircularNode head;

void insertAtHead(int data) {


CircularNode newNode = new CircularNode(data);
if (head == null) {
head = newNode;
newNode.next = head;
} else {
CircularNode current = head;
while (current.next != head) {
current = current.next;
}
newNode.next = head;
head = newNode;
current.next = head;
}
}

void append(int data) {


CircularNode newNode = new CircularNode(data);
if (head == null) {
head = newNode;
newNode.next = head;
} else {
CircularNode current = head;
while (current.next != head) {
current = current.next;
}
current.next = newNode;
newNode.next = head;
}
}

void insertA er(CircularNode prevNode, int data) {


if (prevNode == null) {
System.out.println("The given previous node cannot be null");
return;
}
CircularNode newNode = new CircularNode(data);
newNode.next = prevNode.next;
prevNode.next = newNode;
}

void delete(int key) {


CircularNode current = head;
CircularNode previous = null;
if (current != null && current.data == key) {
if (current.next == head) {
head = null;
} else {
previous = head;
while (previous.next != head) {
previous = previous.next;
}
head = current.next;
previous.next = head;
}
return;
}
while (current.next != head && current.data != key) {
previous = current;
current = current.next;
}
if (current.data == key) {
previous.next = current.next;
}
}

void printList() {
if (head == null) return;
CircularNode current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
LinkedListTest.java:
public class LinkedListTest {
public sta c void main(String[] args) {
// Test Single Linked List
System.out.println("Single Linked List:");
SingleLinkedList sll = new SingleLinkedList();
sll.append(1);
sll.append(2);
sll.append(3);
sll.printList(); // Output: 1 2 3

sll.insertAtHead(0);
sll.printList(); // Output: 0 1 2 3

sll.insertA er(sll.head.next, 1); // Insert 1 a er the second node


sll.printList(); // Output: 0 1 1 2 3

sll.delete(1);
sll.printList(); // Output: 0 1 2 3

// Test Double Linked List


System.out.println("Double Linked List:");
DoubleLinkedList dll = new DoubleLinkedList();
dll.append(1);
dll.append(2);
dll.append(3);
dll.printList(); // Output: 1 2 3

dll.insertAtHead(0);
dll.printList(); // Output: 0 1 2 3

dll.insertA er(dll.head.next, 1); // Insert 1 a er the second node


dll.printList(); // Output: 0 1 1 2 3

dll.delete(1);
dll.printList(); // Output: 0 1 2 3

// Test Circular Linked List


System.out.println("Circular Linked List:");
CircularLinkedList cll = new CircularLinkedList();
cll.append(1);
cll.append(2);
cll.append(3);
cll.printList(); // Output: 1 2 3

cll.insertAtHead(0);
cll.printList(); // Output: 0 1 2 3

cll.insertA er(cll.head.next, 1); // Insert 1 a er the second node


cll.printList(); // Output: 0 1 1 2 3

cll.delete(1);
cll.printList(); // Output: 0 1 2 3
}
}
Compile the Java files:
javac Node.java SingleLinkedList.java DoubleNode.java DoubleLinkedList.java
CircularNode.java CircularLinkedList.java LinkedListTest.java
Run the LinkedListTest class:
java LinkedListTest
OUTPUT:
Single Linked List:
123
0123
01123
0123

Double Linked List:


123
0123
01123
0123

Circular Linked List:


123
0123
01123
0123
WEEK 4
AIM: To develop a program to perform opera ons of Stack and Queue using
Linked Lists.
SOURCE CODE:
// Node class for Linked List
class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}
// Stack class using Linked List
class Stack {
private Node top;

public Stack() {
top = null;
}

public boolean isEmpty() {


return top == null;
}
public void push(int value) {
Node newNode = new Node(value);
newNode.next = top;
top = newNode;
System.out.println("Pushed " + value + " into the stack.");
}

public int pop() {


if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop.");
return -1;
}
int value = top.data;
top = top.next;
return value;
}

public int peek() {


if (isEmpty()) {
System.out.println("Stack is empty. Cannot peek.");
return -1;
}
return top.data;
}
}
// Queue class using Linked List
class Queue {
private Node front;
private Node rear;

public Queue() {
front = rear = null;
}

public boolean isEmpty() {


return front == null;
}

public void enqueue(int value) {


Node newNode = new Node(value);
if (isEmpty()) {
front = rear = newNode;
} else {
rear.next = newNode;
rear = newNode;
}
System.out.println("Inserted " + value + " into the queue.");
}

public int dequeue() {


if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1;
}
int value = front.data;
front = front.next;
if (front == null) {
rear = null;
}
return value;
}

public int peek() {


if (isEmpty()) {
System.out.println("Queue is empty. Cannot peek.");
return -1;
}
return front.data;
}
}
import java.u l.Scanner;

public class Main {


public sta c void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Stack opera ons
System.out.println("Stack opera ons:");
Stack stack = new Stack();
while (true) {
System.out.println("Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value to push:");
int valueToPush = scanner.nextInt();
stack.push(valueToPush);
break;
case 2:
System.out.println("Popped element: " + stack.pop());
break;
case 3:
System.out.println("Top element: " + stack.peek());
break;
case 4:
System.out.println("Exi ng stack opera ons.");
break;
default:
System.out.println("Invalid choice. Try again.");
}
if (choice == 4) break;
}

// Queue opera ons


System.out.println("Queue opera ons:");
Queue queue = new Queue();
while (true) {
System.out.println("Choose an opera on: 1-Enqueue, 2-Dequeue, 3-
Peek, 4-Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value to enqueue:");
int valueToEnqueue = scanner.nextInt();
queue.enqueue(valueToEnqueue);
break;
case 2:
System.out.println("Dequeued element: " + queue.dequeue());
break;
case 3:
System.out.println("Front element: " + queue.peek());
break;
case 4:
System.out.println("Exi ng queue opera ons.");
break;
default:
System.out.println("Invalid choice. Try again.");
}
if (choice == 4) break;
}
scanner.close();
}
}
OUTPUT:
Stack opera ons:
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
10
Pushed 10 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
20
Pushed 20 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
30
Pushed 30 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
1
Enter value to push:
40
Pushed 40 into the stack.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Popped element: 30
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
3
Top element: 20
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Popped element: 20
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Popped element: 10
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
2
Stack is empty. Cannot pop.
Choose an opera on: 1-Push, 2-Pop, 3-Peek, 4-Exit
4
Exi ng stack opera ons.
Queue opera ons:
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
1
Enter value to enqueue:
5
Inserted 5 into the queue.
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
1
Enter value to enqueue:
10
Inserted 10 into the queue.
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
1
Enter value to enqueue:
15
Inserted 15 into the queue.
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
1
Queue is empty. Cannot enqueue 20
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
3
Front element: 5
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
2
Dequeued element: 5
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
2
Dequeued element: 10
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
2
Dequeued element: 15
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
2
Queue is empty. Cannot dequeue.
Choose an opera on: 1-Enqueue, 2-Dequeue, 3-Peek, 4-Exit
4
Exi ng queue opera ons.
WEEK 5
AIM: To develop programs to implement Stack applica ons.
SOURCE CODE:
a. Balanced Parentheses Checking
import java.u l.Stack;
public class BalancedParentheses {
public sta c boolean isBalanced(String expression) {
Stack<Character> stack = new Stack<>();
for (char ch : expression.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if (!isMatchingPair(top, ch)) {
return false;
}
}
}
return stack.isEmpty();
}
private sta c boolean isMatchingPair(char opening, char closing) {
return (opening == '(' && closing == ')') ||
(opening == '{' && closing == '}') ||
(opening == '[' && closing == ']');
}
public sta c void main(String[] args) {
String expression = "{[()]}";
System.out.println("Is balanced: " + isBalanced(expression));
expression = "{[(])}";
System.out.println("Is balanced: " + isBalanced(expression));
}
}
b. Infix to Pos ix Conversion
import java.u l.Stack;
public class InfixToPos ix {
public sta c String infixToPos ix(String infix) {
Stack<Character> stack = new Stack<>();
StringBuilder pos ix = new StringBuilder();
for (char ch : infix.toCharArray()) {
if (Character.isLe erOrDigit(ch)) {
pos ix.append(ch);
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
pos ix.append(stack.pop());
}
stack.pop();
} else {
// operator
while(!stack.isEmpty()&&precedence(ch) <= precedence(stack.peek())) {
pos ix.append(stack.pop());
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
pos ix.append(stack.pop());
}
return pos ix.toString();
}
private sta c int precedence(char op) {
switch (op) {
case '+':
case '-': return 1;
case '*':
case '/': return 2;
case '^': return 3;
}
return -1;
}
public sta c void main(String[] args) {
String infix = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println("Pos ix: " + infixToPos ix(infix));
}
}
c. Pos ix Expression Evalua on
import java.u l.Stack;

public class Pos ixEvalua on {


public sta c int evaluatePos ix(String pos ix) {
Stack<Integer> stack = new Stack<>();

for (char ch : pos ix.toCharArray()) {


if (Character.isDigit(ch)) {
stack.push(ch - '0');
} else {
int b = stack.pop();
int a = stack.pop();
switch (ch) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
}
}
}

return stack.pop();
}

public sta c void main(String[] args) {


String pos ix = "231*+9-";
System.out.println("Result: " + evaluatePos ix(pos ix));
}
}
d. Undo Mechanism in Text Editors
import java.u l.Stack;

public class UndoMechanism {


private Stack<String> history = new Stack<>();
private String currentText = "";

public void type(String text) {


history.push(currentText);
currentText += text;
}

public void undo() {


if (!history.isEmpty()) {
currentText = history.pop();
}
}

public String getText() {


return currentText;
}

public sta c void main(String[] args) {


UndoMechanism editor = new UndoMechanism();

editor.type("Hello");
System.out.println("Current text: " + editor.getText());

editor.type(" World");
System.out.println("Current text: " + editor.getText());

editor.undo();
System.out.println("A er undo: " + editor.getText());

editor.undo();
System.out.println("A er undo: " + editor.getText());
}
}
e. Func on Call Management in Recursion
import java.u l.Stack;

public class Func onCallManagement {


private sta c Stack<String> callStack = new Stack<>();

public sta c void func onA() {


callStack.push("Func on A");
func onB();
callStack.pop();
}

public sta c void func onB() {


callStack.push("Func on B");
func onC();
callStack.pop();
}

public sta c void func onC() {


callStack.push("Func on C");
System.out.println("Current call stack: " + callStack);
callStack.pop();
}

public sta c void main(String[] args) {


func onA();
}
}
OUTPUT:
a.
Is balanced: true
Is balanced: false
b.
Pos ix: abcd^e-fgh*+^*+i-
c.
Result: -4
d.
Current text: Hello
Current text: Hello World
A er undo: Hello
A er undo:
e.
Current call stack: [Func on A, Func on B, Func on C]
WEEK 6
AIM: To implement Circular Queues.
SOURCE CODE:
public class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;

// Constructor to ini alize the queue


public CircularQueue(int capacity) {
this.capacity = capacity;
queue = new int[capacity];
front = 0;
rear = -1;
size = 0;
}

// Check if the queue is empty


public boolean isEmpty() {
return size == 0;
}

// Check if the queue is full


public boolean isFull() {
return size == capacity;
}
// Add an element to the rear of the queue
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full. Cannot enqueue " + item);
return;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
size++;
System.out.println("Enqueued " + item);
}

// Remove an element from the front of the queue


public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue.");
return -1; // or throw excep on
}
int item = queue[front];
front = (front + 1) % capacity;
size--;
return item;
}
// Get the front element without removing it
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot peek.");
return -1; // or throw excep on
}
return queue[front];
}

// Print the elements of the queue


public void display() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return;
}
System.out.print("Queue elements: ");
for (int i = 0; i < size; i++) {
System.out.print(queue[(front + i) % capacity] + " ");
}
System.out.println();
}

public sta c void main(String[] args) {


CircularQueue cq = new CircularQueue(5);
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.enqueue(40);
cq.enqueue(50);
cq.enqueue(60); // Should display that the queue is full

cq.display();

System.out.println("Dequeued: " + cq.dequeue());


System.out.println("Dequeued: " + cq.dequeue());

cq.display();

cq.enqueue(60);
cq.enqueue(70);

cq.display();

System.out.println("Front element: " + cq.peek());


}
}
OUTPUT:
Enqueued 10
Enqueued 20
Enqueued 30
Enqueued 40
Enqueued 50
Queue is full. Cannot enqueue 60
Queue elements: 10 20 30 40 50
Dequeued: 10
Dequeued: 20
Queue elements: 30 40 50
Enqueued 60
Enqueued 70
Queue elements: 30 40 50 60 70
Front element: 30
WEEK 7
AIM: To implement various Searching techniques.
SOURCE CODE:
a. Linear Search
public class LinearSearch {
public sta c int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Target found
}
}
return -1; // Target not found
}

public sta c void main(String[] args) {


int[] arr = {5, 3, 8, 6, 7};
int target = 6;
int index = linearSearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
b. Binary Search
import java.u l.Arrays;

public class BinarySearch {


public sta c int binarySearch(int[] arr, int target) {
int le = 0;
int right = arr.length - 1;

while (le <= right) {


int mid = le + (right - le ) / 2;

if (arr[mid] == target) {
return mid; // Target found
}

if (arr[mid] < target) {


le = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Target not found
}

public sta c void main(String[] args) {


int[] arr = {3, 5, 6, 7, 8}; // Must be sorted for binary search
int target = 6;
int index = binarySearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
c. Fibonacci Search
public class FibonacciSearch {
public sta c int fibonacciSearch(int[] arr, int target) {
int n = arr.length;
int fibM = 0; // Fibonacci m-1
int fibM1 = 1; // Fibonacci m-2
int fibM2 = 0; // Fibonacci m-3

// Find the smallest Fibonacci number greater than or equal to n


while (fibM < n) {
fibM = fibM1 + fibM2;
fibM2 = fibM1;
fibM1 = fibM;
}
// Marks the eliminated range from front
int offset = -1;

// While there are elements to be inspected.


while (fibM > 1) {
// Check if fibM1 is a valid index
int i = Math.min(offset + fibM2, n - 1);

if (arr[i] < target) {


// Move the range to the right
fibM = fibM1;
fibM1 = fibM2;
fibM2 = fibM - fibM1;
offset = i;
} else if (arr[i] > target) {
// Move the range to the le
fibM = fibM2;
fibM1 = fibM1 - fibM2;
fibM2 = fibM - fibM1;
} else {
// Target found
return i;
}
}
// Comparing the last element with target
if (fibM1 == 1 && arr[offset + 1] == target) {
return offset + 1;
}

// Target not found


return -1;
}

public sta c void main(String[] args) {


int[] arr = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100};
int target = 85;
int index = fibonacciSearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}
OUTPUT:
a.
Element found at index: 3
b.
Element found at index: 2
c.
Element found at index: 8
WEEK 8
AIM: To develop programs for different Sor ng techniques
SOURCE CODE:
a. Bubble Sort
public class BubbleSort {
public sta c void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no two elements were swapped, break the loop
if (!swapped) break;
}
}

public sta c void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
bubbleSort(arr);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
b. Selec on Sort
public class Selec onSort {
public sta c void selec onSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public sta c void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
selec onSort(arr);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
c. Inser on Sort
public class Inser onSort {
public sta c void inser onSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key, to one posi on
ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

public sta c void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
inser onSort(arr);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
d. Merge Sort
public class MergeSort {
public sta c void mergeSort(int[] arr, int le , int right) {
if (le < right) {
int mid = (le + right) / 2;
mergeSort(arr, le , mid);
mergeSort(arr, mid + 1, right);
merge(arr, le , mid, right);
}
}

private sta c void merge(int[] arr, int le , int mid, int right) {
int n1 = mid - le + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];

System.arraycopy(arr, le , L, 0, n1);
System.arraycopy(arr, mid + 1, R, 0, n2);

int i = 0, j = 0;
int k = le ;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

public sta c void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
mergeSort(arr, 0, arr.length - 1);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
e. Quick Sort
public class QuickSort {
public sta c void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = par on(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

private sta c int par on(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

// Swap arr[i + 1] and arr[high] (or pivot)


int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1;
}

public sta c void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
quickSort(arr, 0, arr.length - 1);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
f. Heap Sort
public class HeapSort {
public sta c void heapSort(int[] arr) {
int n = arr.length;

// Build max heap


for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}

// Extract elements one by one from heap


for (int i = n - 1; i >= 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Call max heapify on the reduced heap
heapify(arr, i, 0);
}
}

private sta c void heapify(int[] arr, int n, int i) {


int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;

if (l < n && arr[l] > arr[largest]) {


largest = l;
}

if (r < n && arr[r] > arr[largest]) {


largest = r;
}

if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;

heapify(arr, n, largest);
}
}

public sta c void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
heapSort(arr);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
g. Radix Sort
import java.u l.Arrays;

public class RadixSort {


// Coun ng sort based on significant places
private sta c void coun ngSort(int[] arr, int exp) {
int n = arr.length;
int[] output = new int[n];
int[] count = new int[10];

Arrays.fill(count, 0);

// Store count of occurrences


for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}

// Change count[i] so that count[i] now contains actual posi on of this


digit in output[]
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}

// Build the output array


for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Copy the output array to arr[], so that arr[] contains sorted numbers
according to current digit
System.arraycopy(output, 0, arr, 0, n);
}

// Main func on to implement radix sort


public sta c void radixSort(int[] arr) {
int max = Arrays.stream(arr).max().getAsInt();

// Do coun ng sort for every digit. The exp is 10^i where i is the current
digit number
for (int exp = 1; max / exp > 0; exp *= 10) {
coun ngSort(arr, exp);
}
}

public sta c void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
radixSort(arr);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
OUTPUT:

Sorted array:
11 12 22 25 64
WEEK 9
AIM: To develop a program to represent a Tree data structure.
SOURCE CODE:
// Class represen ng a node in the binary tree
class TreeNode {
int value;
TreeNode le , right;

// Constructor
public TreeNode(int item) {
value = item;
le = right = null;
}
}

// Class represen ng the binary tree


class BinaryTree {
TreeNode root;

// Constructor
public BinaryTree() {
root = null;
}

// Method to perform in-order traversal


void inOrderTraversal(TreeNode node) {
if (node != null) {
inOrderTraversal(node.le );
System.out.print(node.value + " ");
inOrderTraversal(node.right);
}
}

// Method to start in-order traversal from the root


void printInOrder() {
inOrderTraversal(root);
}

// Method to insert a new node


TreeNode insert(TreeNode node, int value) {
if (node == null) {
node = new TreeNode(value);
return node;
}

if (value < node.value) {


node.le = insert(node.le , value);
} else if (value > node.value) {
node.right = insert(node.right, value);
}
return node;
}

// Wrapper method for inser ng a new node


void insert(int value) {
root = insert(root, value);
}

public sta c void main(String[] args) {


BinaryTree tree = new BinaryTree();

// Inser ng nodes into the tree


tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

// Prin ng the in-order traversal of the tree


System.out.println("In-order traversal of the binary tree:");
tree.printInOrder();
}
}
OUTPUT:
In-order traversal of the binary tree:
20 30 40 50 60 70 80
WEEK 10
AIM: To develop a program to demonstrate opera ons on Binary Search Tree.
SOURCE CODE:
// Class represen ng a node in the binary search tree
class TreeNode {
int value;
TreeNode le , right;

// Constructor
public TreeNode(int item) {
value = item;
le = right = null;
}
}

// Class represen ng the binary search tree


class BinarySearchTree {
TreeNode root;

// Constructor
public BinarySearchTree() {
root = null;
}

// Method to insert a new node


TreeNode insert(TreeNode node, int value) {
if (node == null) {
node = new TreeNode(value);
return node;
}

if (value < node.value) {


node.le = insert(node.le , value);
} else if (value > node.value) {
node.right = insert(node.right, value);
}

return node;
}

// Wrapper method for inser on


void insert(int value) {
root = insert(root, value);
}

// Method to search for a node


boolean search(TreeNode node, int value) {
if (node == null) {
return false;
}
if (node.value == value) {
return true;
}
return value < node.value
? search(node.le , value)
: search(node.right, value);
}

// Wrapper method for search


boolean search(int value) {
return search(root, value);
}

// Method to find the minimum value node


TreeNode findMin(TreeNode node) {
while (node.le != null) {
node = node.le ;
}
return node;
}

// Method to delete a node


TreeNode delete(TreeNode root, int value) {
if (root == null) return root;
if (value < root.value) {
root.le = delete(root.le , value);
} else if (value > root.value) {
root.right = delete(root.right, value);
} else {
// Node with only one child or no child
if (root.le == null) return root.right;
else if (root.right == null) return root.le ;

// Node with two children: Get the inorder successor (smallest in the right
subtree)
TreeNode temp = findMin(root.right);

// Copy the inorder successor's content to this node


root.value = temp.value;

// Delete the inorder successor


root.right = delete(root.right, temp.value);
}

return root;
}

// Wrapper method for dele on


void delete(int value) {
root = delete(root, value);
}

// Method for in-order traversal


void inOrderTraversal(TreeNode node) {
if (node != null) {
inOrderTraversal(node.le );
System.out.print(node.value + " ");
inOrderTraversal(node.right);
}
}

// Wrapper method for in-order traversal


void printInOrder() {
inOrderTraversal(root);
}

public sta c void main(String[] args) {


BinarySearchTree bst = new BinarySearchTree();

// Inser ng nodes
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);

// Prin ng the in-order traversal of the BST


System.out.println("In-order traversal of the binary search tree:");
bst.printInOrder();

// Searching for a value


int searchValue = 40;
System.out.println("\nSearching for value " + searchValue + ": " +
(bst.search(searchValue) ? "Found" : "Not Found"));

// Dele ng a node
int deleteValue = 20;
System.out.println("Dele ng value " + deleteValue);
bst.delete(deleteValue);

// Prin ng the in-order traversal of the BST a er dele on


System.out.println("In-order traversal a er dele on:");
bst.printInOrder();
}
}
OUTPUT:
In-order traversal of the binary search tree:
20 30 40 50 60 70 80
Searching for value 40: Found

Dele ng value 20
In-order traversal a er dele on:
30 40 50 60 70 80
WEEK 11
AIM: To demonstrate Graph Traversal Techniques.
SOURCE CODE:
a. Graph Representa on Using Adjacency List
import java.u l.*;

// Class represen ng a graph using adjacency list


class Graph {
private final Map<Integer, List<Integer>> adjacencyList;

// Constructor
public Graph() {
adjacencyList = new HashMap<>();
}

// Add an edge to the graph


public void addEdge(int src, int dest) {
adjacencyList.putIfAbsent(src, new ArrayList<>());
adjacencyList.putIfAbsent(dest, new ArrayList<>());
adjacencyList.get(src).add(dest);
adjacencyList.get(dest).add(src); // Undirected graph
}

// BFS traversal
public void bfs(int start) {
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();

visited.add(start);
queue.add(start);

System.out.println("BFS traversal star ng from node " + start + ":");


while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");

for (int neighbor : adjacencyList.getOrDefault(node, new ArrayList<>())) {


if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
System.out.println();
}

// DFS traversal
public void dfs(int start) {
Set<Integer> visited = new HashSet<>();
System.out.println("DFS traversal star ng from node " + start + ":");
dfsU l(start, visited);
System.out.println();
}

private void dfsU l(int node, Set<Integer> visited) {


visited.add(node);
System.out.print(node + " ");

for (int neighbor : adjacencyList.getOrDefault(node, new ArrayList<>())) {


if (!visited.contains(neighbor)) {
dfsU l(neighbor, visited);
}
}
}

public sta c void main(String[] args) {


Graph graph = new Graph();

// Adding edges to the graph


graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(2, 5);
graph.addEdge(3, 6);
graph.addEdge(3, 7);
// Perform BFS and DFS
graph.bfs(1);
graph.dfs(1);
}
}
OUTPUT:
a.
BFS traversal star ng from node 1:
1234567
DFS traversal star ng from node 1:
1245367
WEEK 12
AIM: To develop a program to find Minimum cost Spanning tree.
SOURCE CODE:
a. Kruskal's Algorithm Implementa on
import java.u l.*;

// Class represen ng an edge in the graph


class Edge implements Comparable<Edge> {
int src, dest, weight;

// Constructor
public Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}

// Comparator for sor ng edges based on weight


@Override
public int compareTo(Edge other) {
return Integer.compare(this.weight, other.weight);
}
}

// Class represen ng the Union-Find data structure


class UnionFind {
private final int[] parent;
private final int[] rank;

// Constructor
public UnionFind(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}

// Find with path compression


public int find(int u) {
if (parent[u] != u) {
parent[u] = find(parent[u]);
}
return parent[u];
}

// Union by rank
public void union(int u, int v) {
int rootU = find(u);
int rootV = find(v);

if (rootU != rootV) {
if (rank[rootU] > rank[rootV]) {
parent[rootV] = rootU;
} else if (rank[rootU] < rank[rootV]) {
parent[rootU] = rootV;
} else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
}

// Class represen ng the Kruskal's Algorithm for finding MST


public class KruskalMST {
public sta c void kruskalMST(List<Edge> edges, int V) {
Collec ons.sort(edges); // Sort edges by weight

UnionFind uf = new UnionFind(V);


List<Edge> mst = new ArrayList<>();

for (Edge edge : edges) {


int rootU = uf.find(edge.src);
int rootV = uf.find(edge.dest);

if (rootU != rootV) {
uf.union(rootU, rootV);
mst.add(edge);
}
}

// Print the edges in the MST


System.out.println("Edges in the Minimum Spanning Tree:");
int totalWeight = 0;
for (Edge edge : mst) {
System.out.println(edge.src + " - " + edge.dest + " : " + edge.weight);
totalWeight += edge.weight;
}
System.out.println("Total weight of MST: " + totalWeight);
}

public sta c void main(String[] args) {


int V = 4; // Number of ver ces
List<Edge> edges = new ArrayList<>();

// Adding edges (src, dest, weight)


edges.add(new Edge(0, 1, 10));
edges.add(new Edge(0, 2, 6));
edges.add(new Edge(0, 3, 5));
edges.add(new Edge(1, 3, 15));
edges.add(new Edge(2, 3, 4));

// Find the MST using Kruskal's algorithm


kruskalMST(edges, V);
}
}
b. Prim's Algorithm Implementa on
import java.u l.*;

// Class represen ng a graph using adjacency list


class PrimGraph {
private final Map<Integer, List<int[]>> adjacencyList;

// Constructor
public PrimGraph() {
adjacencyList = new HashMap<>();
}

// Add an edge to the graph


public void addEdge(int src, int dest, int weight) {
adjacencyList.putIfAbsent(src, new ArrayList<>());
adjacencyList.putIfAbsent(dest, new ArrayList<>());
adjacencyList.get(src).add(new int[]{dest, weight});
adjacencyList.get(dest).add(new int[]{src, weight}); // Undirected graph
}

// Prim's algorithm for MST


public void primMST(int start) {
PriorityQueue<int[]> minHeap = new
PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
Set<Integer> visited = new HashSet<>();
int totalWeight = 0;

// Add the star ng node


minHeap.add(new int[]{start, 0});

System.out.println("Edges in the Minimum Spanning Tree:");


while (!minHeap.isEmpty()) {
int[] edge = minHeap.poll();
int node = edge[0];
int weight = edge[1];

if (!visited.contains(node)) {
visited.add(node);
totalWeight += weight;

if (weight > 0) {
System.out.println("Node " + node + " with weight " + weight);
}
for (int[] neighbor : adjacencyList.getOrDefault(node, new
ArrayList<>())) {
if (!visited.contains(neighbor[0])) {
minHeap.add(neighbor);
}
}
}
}
System.out.println("Total weight of MST: " + totalWeight);
}

public sta c void main(String[] args) {


PrimGraph graph = new PrimGraph();

// Adding edges (src, dest, weight)


graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 6);
graph.addEdge(0, 3, 5);
graph.addEdge(1, 3, 15);
graph.addEdge(2, 3, 4);

// Find the MST using Prim's algorithm


graph.primMST(0);
}
}
OUTPUT:
a.
Edges in the Minimum Spanning Tree:
0-3:5
2-3:4
0 - 1 : 10
Total weight of MST: 19
b.
Edges in the Minimum Spanning Tree:
Node 0 with weight 0
Node 3 with weight 5
Node 2 with weight 4
Node 1 with weight 10
Total weight of MST: 19
BEYOND EXPERIENTIAL LEARNING
A project that demonstrates Hospital Management System. This project will
cover various features such as managing pa ents, doctors, and appointments,
and it will involve different cases like adding, upda ng, and viewing informa on.
Overview
 Features:
o Add and view pa ents
o Add and view doctors
o Schedule and view appointments
 Technology: Java with console-based interac ons
Java Source Code
Main Applica on
import java.u l.*;

public class HospitalManagementSystem {

public sta c void main(String[] args) {


Scanner scanner = new Scanner(System.in);
Hospital hospital = new Hospital();

while (true) {
System.out.println("Hospital Management System");
System.out.println("1. Add Pa ent");
System.out.println("2. View Pa ents");
System.out.println("3. Add Doctor");
System.out.println("4. View Doctors");
System.out.println("5. Schedule Appointment");
System.out.println("6. View Appointments");
System.out.println("7. Exit");
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter pa ent name: ");
String pa entName = scanner.nextLine();
System.out.print("Enter pa ent age: ");
int pa entAge = scanner.nextInt();
scanner.nextLine(); // Consume newline
hospital.addPa ent(new Pa ent(pa entName, pa entAge));
break;
case 2:
hospital.viewPa ents();
break;
case 3:
System.out.print("Enter doctor name: ");
String doctorName = scanner.nextLine();
System.out.print("Enter doctor specializa on: ");
String specializa on = scanner.nextLine();
hospital.addDoctor(new Doctor(doctorName, specializa on));
break;
case 4:
hospital.viewDoctors();
break;
case 5:
System.out.print("Enter pa ent name: ");
String pname = scanner.nextLine();
System.out.print("Enter doctor name: ");
String dname = scanner.nextLine();
System.out.print("Enter appointment date (YYYY-MM-DD): ");
String date = scanner.nextLine();
hospital.scheduleAppointment(pname, dname, date);
break;
case 6:
hospital.viewAppointments();
break;
case 7:
System.out.println("Exi ng...");
scanner.close();
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
Hospital Class
import java.u l.*;

class Hospital {
private final List<Pa ent> pa ents = new ArrayList<>();
private final List<Doctor> doctors = new ArrayList<>();
private final List<Appointment> appointments = new ArrayList<>();

public void addPa ent(Pa ent pa ent) {


pa ents.add(pa ent);
System.out.println("Pa ent added: " + pa ent);
}

public void viewPa ents() {


System.out.println("Pa ents:");
for (Pa ent pa ent : pa ents) {
System.out.println(pa ent);
}
}

public void addDoctor(Doctor doctor) {


doctors.add(doctor);
System.out.println("Doctor added: " + doctor);
}

public void viewDoctors() {


System.out.println("Doctors:");
for (Doctor doctor : doctors) {
System.out.println(doctor);
}
}

public void scheduleAppointment(String pa entName, String doctorName,


String date) {
Pa ent pa ent = findPa entByName(pa entName);
Doctor doctor = findDoctorByName(doctorName);

if (pa ent != null && doctor != null) {


Appointment appointment = new Appointment(pa ent, doctor, date);
appointments.add(appointment);
System.out.println("Appointment scheduled: " + appointment);
} else {
System.out.println("Pa ent or Doctor not found.");
}
}

public void viewAppointments() {


System.out.println("Appointments:");
for (Appointment appointment : appointments) {
System.out.println(appointment);
}
}

private Pa ent findPa entByName(String name) {


for (Pa ent pa ent : pa ents) {
if (pa ent.getName().equalsIgnoreCase(name)) {
return pa ent;
}
}
return null;
}

private Doctor findDoctorByName(String name) {


for (Doctor doctor : doctors) {
if (doctor.getName().equalsIgnoreCase(name)) {
return doctor;
}
}
return null;
}
}
Pa ent Class
class Pa ent {
private final String name;
private final int age;

public Pa ent(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

@Override
public String toString() {
return "Pa ent{name='" + name + "', age=" + age + "}";
}
}
Doctor Class
class Doctor {
private final String name;
private final String specializa on;

public Doctor(String name, String specializa on) {


this.name = name;
this.specializa on = specializa on;
}

public String getName() {


return name;
}

@Override
public String toString() {
return "Doctor{name='" + name + "', specializa on='" + specializa on + "'}";
}
}
Appointment Class
class Appointment {
private final Pa ent pa ent;
private final Doctor doctor;
private final String date;

public Appointment(Pa ent pa ent, Doctor doctor, String date) {


this.pa ent = pa ent;
this.doctor = doctor;
this.date = date;
}
@Override
public String toString() {
return "Appointment{pa ent=" + pa ent + ", doctor=" + doctor + ", date='"
+ date + "'}";
}
}
Output
Hospital Management System
1. Add Pa ent
2. View Pa ents
3. Add Doctor
4. View Doctors
5. Schedule Appointment
6. View Appointments
7. Exit
Enter your choice: 1
Enter pa ent name: John Doe
Enter pa ent age: 30
Pa ent added: Pa ent{name='John Doe', age=30}

Hospital Management System


1. Add Pa ent
2. View Pa ents
3. Add Doctor
4. View Doctors
5. Schedule Appointment
6. View Appointments
7. Exit
Enter your choice: 3
Enter doctor name: Dr. Smith
Enter doctor specializa on: Cardiologist
Doctor added: Doctor{name='Dr. Smith', specializa on='Cardiologist'}

Hospital Management System


1. Add Pa ent
2. View Pa ents
3. Add Doctor
4. View Doctors
5. Schedule Appointment
6. View Appointments
7. Exit
Enter your choice: 5
Enter pa ent name: John Doe
Enter doctor name: Dr. Smith
Enter appointment date (YYYY-MM-DD): 2024-08-15
Appointment scheduled: Appointment{pa ent=Pa ent{name='John Doe',
age=30}, doctor=Doctor{name='Dr. Smith', specializa on='Cardiologist'},
date='2024-08-15'}

Hospital Management System


1. Add Pa ent
2. View Pa ents
3. Add Doctor
4. View Doctors
5. Schedule Appointment
6. View Appointments
7. Exit
Enter your choice: 6
Appointments:
Appointment{pa ent=Pa ent{name='JohnDoe',age=30},doctor=Doctor{name='
Dr. Smith', specializa on='Cardiologist'}, date='2024-08-15'}
Exercises for Hospital Management System

1. Add Patient and Doctor Details

2. Implement Appointment Cancellation

3. Search and Filter Patients and Doctors

4. Generate Appointment Reports

5. Validate User Input

6. Implement a Graphical User Interface (GUI)

7. Implement User Authentication

8. Add a Feature for Doctor Availability

Sample Exercise Output

Enter patient name: John Doe

Enter patient age: 30

Enter patient address: 123 Main St

Enter patient contact number: 555-1234

Patient added: Patient{name='John Doe', age=30, address='123 Main St',


contactNumber='555-1234'}

Enter doctor name: Dr. Smith

Enter doctor specialization: Cardiologist

Enter doctor address: 456 Elm St

Enter doctor contact number: 555-5678

Doctor added: Doctor{name='Dr. Smith', specialization='Cardiologist',


address='456 Elm St', contactNumber='555-5678'}

You might also like