You are on page 1of 54

A

LAB REPORT

ON

Data Structure and Algorithm

By

Sagar Kandel

Symbol No: 13677/21

Submitted to:

Mr. Nimesh Pokhrel

Department of Management

Nepal Commerce Campus

In partial fulfillment of the requirements for the Course

Data Structure and Algorithm

MinBhawan, Kathmandu

Aug, 2023
Contents

1. Program to insert nodes at the beginning, at particular and end of Singly


Linked List.............................................................................................................4
1.1 Source code..............................................................................................4
1.2 Output window.........................................................................................6
2. Program to delete first and last node of a Singly Linked List............................7
2.1 Source code..............................................................................................7
2.2 Output Window........................................................................................7
3. Program to delete a node at any particular position of a Singly Linked List.....8
3.1 Source code..............................................................................................8
3.2 Output window.......................................................................................10
4. Program to insert a node at the beginning of Singly Linked List and then
search a particular value is in the list or not.........................................................11
4.1 Source code............................................................................................11
4.2 Output window.......................................................................................12
5. Program to insert nodes at different positions of Doubly Linked List.............13
5.1 Source code............................................................................................13
5.2 Output window.......................................................................................15
6. Program to delete nodes from different positions of Doubly Linked List.......16
6.1 Source code............................................................................................16
6.2 Output window.......................................................................................18
7. Program to insert nodes at different positions of Singly Circular Linked List.
..............................................................................................................................19
7.1 Source code............................................................................................19
7.2 Output window.......................................................................................21
8. Program to delete nodes from different positions of Doubly Circular Linked
List........................................................................................................................22
8.1 Source code............................................................................................22
8.2 Output window.......................................................................................24
9. Program to implement Stack............................................................................25
9.1 Source code............................................................................................25
9.2 Output window.......................................................................................26
10. Program to implement Queue........................................................................27
10.1 Source code..........................................................................................27

1|P a g e
10.2 Output window.....................................................................................28
11. Program to implement Priority Queue...........................................................29
11.1 Source code..........................................................................................29
11.2 Output window.....................................................................................29
12. Program to calculate and display factorial of a number using recursion.......30
12.1 Source code..........................................................................................30
12.2 Output window.....................................................................................30
13. Program to display 7th term of Fibonacci series.reak to exit a loop..............31
13.1 Source code..........................................................................................31
13.2 Output window.....................................................................................31
14. Program to calculate product of two integer..................................................32
14.1 Source code..........................................................................................32
14.2 Output window.....................................................................................32
15. Program to implement Tower of Hanoi problem with 5 disks.......................33
15.1 Source Code.........................................................................................33
15.2 Output window.....................................................................................34
16. Program to implement binary tree using linked list.......................................34
16.1 Source Code.........................................................................................34
16.2 Output window.....................................................................................37
17. Program to implement Depth first traversal of Binary tree............................38
17.1 Source code..........................................................................................38
17.2 Output window.....................................................................................39
18. Program to implement Dijkstra’s Algorithm.................................................39
18.1 Source code........................................................................................39
18.1 Output window.....................................................................................40
19. Program to implement Kruskal’s Algorithm..................................................41
19.1 Source Code.........................................................................................41
19.2 Output window.....................................................................................43
20. Programs to implement Merge sorting algorithm..........................................44
20.1 Source code..........................................................................................44
20.2 Output window.....................................................................................45
21. Programs to implement Radix sorting algorithm...........................................46
21.1 Source code..........................................................................................46
21.2 Output window.....................................................................................47
22. Programs to implement Heap sorting algorithm............................................47

2|P a g e
22.1 Source code..........................................................................................47
22.2 Output window.....................................................................................49
23. Program to implement Linear Probing...........................................................49
23.1 Source code..........................................................................................49
23.2 Output window.....................................................................................54

3|P a g e
1. Program to insert nodes at the beginning, at particular and end of
Singly Linked List.
1.1 Source code

class singlyLinkedlist {
static class Node {
public int data;
public Node nextNode;
public Node(int data) {
this.data = data;
} }
static Node GetNode(int data) {
return new Node(data);
} static Node InsertPos(Node headNode, int position, int data) {
Node head = headNode;
if (position < 1)
System.out.print("Invalid position");
if (position == 1) {
Node newNode = new Node(data);
newNode.nextNode = headNode;
head = newNode;
} else {
while (position-- != 0) {
if (position == 1) {
Node newNode = GetNode(data);

newNode.nextNode = headNode.nextNode;
headNode.nextNode = newNode;
break;
}
headNode = headNode.nextNode;
}
if (position != 1)
System.out.print("Position out of range");

4|P a g e
}
return head;
}
static void PrintList(Node node) {
while (node != null) {
System.out.print(node.data);
node = node.nextNode;
if (node != null)
System.out.print(",");
}
System.out.println();
}
public static void main(String[] args) {
Node head = GetNode(3);
head.nextNode = GetNode(5);
head.nextNode.nextNode = GetNode(8);
head.nextNode.nextNode.nextNode = GetNode(10);
System.out.print("Linked list before insertion: ");
PrintList(head);
int data = 12, pos = 3;
head = InsertPos(head, pos, data);
System.out.print("Linked list after" + " insertion of 12 at position 3: ");
PrintList(head);
data = 1;
pos = 1;
head = InsertPos(head, pos, data);
System.out.print("Linked list after" + "insertion of 1 at position 1: ");
PrintList(head);
data = 15;
pos = 7;
head = InsertPos(head, pos, data);
System.out.print("Linked list after" + " insertion of 15 at position 7: ");
PrintList(head);
}
}

5|P a g e
1.2 Output window

6|P a g e
2. Program to delete first and last node of a Singly Linked List.
2.1 Source code

import java.util.*;
public class delete {
public static void main(String[] args) {
LinkedList<String> l_list = new LinkedList<String>();
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("Pink");
l_list.add("orange");
System.out.println("The Original linked list: " + l_list);
Object firstElement = l_list.removeFirst();
System.out.println("Element removed: "+ firstElement);
Object lastElement = l_list.removeLast();
System.out.println("Element removed: "+ lastElement);
System.out.println("The New linked list: " + l_list);
} }

2.2 Output Window

7|P a g e
3. Program to delete a node at any particular position of a Singly
Linked List.
3.1 Source code

public class deletespecific


{
Node head;
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void deleteNode(int position)
{
if (head == null)
return;
Node temp = head;
if (position == 0)
{
head = temp.next;
return;
}
for (int i=0; temp!=null && i<position-1; i++)
temp = temp.next;

8|P a g e
if (temp == null || temp.next == null)
return;
Node next1 = temp.next.next;
temp.next = next1;
}
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}
public static void main(String[] args)
{
deletespecific llist = new deletespecific();
llist.push(9);
llist.push(6);
llist.push(8);
llist.push(18);
System.out.println("\nCreated Linked list is: ");
llist.printList();
llist.deleteNode(2);
System.out.println("\nLinked List after Deletion at position 2: ");
llist.printList();
}
}

3.2 Output window

9|P a g e
4. Program to insert a node at the beginning of Singly Linked List
and then search a particular value is in the list or not.
4.1 Source code

public class SearchLinkedList {


class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null; } }
public Node head = null;
public Node tail = null;
public void addNode(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
tail = newNode; }
else {
tail.next = newNode;
tail = newNode;
} }
public void searchNode(int data) {
Node current = head;
int i = 1;
boolean flag = false;
if(head == null) {
System.out.println("List is empty"); }
else {
while(current != null) {
if(current.data == data) {
flag = true;
break; }
i++;
current = current.next; } }
10 | P a g e
if(flag)
System.out.println("The particular Element is present in the list at the position
: " + i);
else
System.out.println("The particularElement is not present in the list"); }
public static void main(String[] args) {
SearchLinkedList sList = new SearchLinkedList();
sList.addNode(49);
sList.addNode(50);
sList.addNode(51);
sList.addNode(52);
sList.searchNode(53);
sList.searchNode(49); }}

4.2 Output window

11 | P a g e
5. Program to insert nodes at different positions of Doubly Linked
List.
5.1 Source code

class Node {
int data;
Node next;
Node prev; };
class LinkedList {
Node head;
LinkedList(){
head = null; }
void push_back(int newElement) {
Node newNode = new Node();
newNode.data = newElement;
newNode.next = null;
newNode.prev = null;
if(head == null) {
head = newNode;
} else {
Node temp = new Node();
temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = newNode;
newNode.prev = temp; } }
void push_at(int newElement, int position) {
Node newNode = new Node();
newNode.data = newElement;
newNode.next = null;
newNode.prev = null;
if(position < 1) {
System.out.print("\nposition should be >= 1.");
} else if (position == 1) {
newNode.next = head;
12 | P a g e
head.prev = newNode;
head = newNode;
} else {
Node temp = new Node();
temp = head;
for(int i = 1; i < position-1; i++) {
if(temp != null) {
temp = temp.next; } }
if(temp != null) {
newNode.next = temp.next;
newNode.prev = temp;
temp.next = newNode;
if(newNode.next != null)
newNode.next.prev = newNode;
} else {
System.out.print("\nThe previous node is null."); } } }
void PrintList() {
Node temp = new Node();
temp = this.head;
if(temp != null) {
System.out.print("The list contains: ");
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
} else {
System.out.println("The list is empty."); } } };
public class adddoubly {
public static void main(String[] args) {
LinkedList MyList = new LinkedList();
MyList.push_back(1);
MyList.push_back(2);
MyList.push_back(3);
MyList.PrintList();

13 | P a g e
MyList.push_at(25, 1);
MyList.PrintList();
MyList.push_at(12, 3);
MyList.PrintList(); }} }

5.2 Output window

14 | P a g e
6. Program to delete nodes from different positions of Doubly
Linked List.
6.1 Source code

class Node {
int data;
Node next;
Node prev; };
class LinkedList {
Node head;
LinkedList(){
head = null; }
void push_back(int newElement) {
Node newNode = new Node();
newNode.data = newElement;
newNode.next = null;
newNode.prev = null;
if(head == null) {
head = newNode;
} else {
Node temp = new Node();
temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = newNode;
newNode.prev = temp; } }
void pop_at(int position) {
if(position < 1) {
System.out.print("\nposition should be >= 1.");
} else if (position == 1 && head != null) {
Node nodeToDelete = head;
head = head.next;
nodeToDelete = null;
if (head != null)
head.prev = null;
15 | P a g e
} else {
Node temp = new Node();
temp = head;
for(int i = 1; i < position-1; i++) {
if(temp != null) {
temp = temp.next; } }
if(temp != null && temp.next != null) {
Node nodeToDelete = temp.next;
temp.next = temp.next.next;
if(temp.next.next != null)
temp.next.next.prev = temp.next;
nodeToDelete = null;
} else {
System.out.print("\nThe node is already null."); } } }
void PrintList() {
Node temp = new Node();
temp = this.head;
if(temp != null) {
System.out.print("The list contains: ");
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next; }
System.out.println();
} else {
System.out.println("The list is empty."); } } };
public class deleteDoublyLinkedlist {
public static void main(String[] args) {
LinkedList MyList = new LinkedList();
MyList.push_back(1);
MyList.push_back(2);
MyList.push_back(3);
MyList.PrintList();
MyList.pop_at(3);
MyList.PrintList();
MyList.pop_at(0);

16 | P a g e
MyList.PrintList();
}
}

6.2 Output window

17 | P a g e
7. Program to insert nodes at different positions of Singly Circular
Linked List.
7.1 Source code

class Node {
int data;
Node next; };
class LinkedList {
Node head;
LinkedList(){
head = null; }
void push_back(int newElement) {
Node newNode = new Node();
newNode.data = newElement;
newNode.next = null;
if(head == null) {
head = newNode;
newNode.next = head;
} else {
Node temp = new Node();
temp = head;
while(temp.next != head)
temp = temp.next;
temp.next = newNode;
newNode.next = head; } }
void push_at(int newElement, int position) {
Node newNode = new Node();
newNode.data = newElement;
newNode.next = null;
Node temp = head;
int NoOfElements = 0;
if(temp != null) {
NoOfElements++;
temp = temp.next; }
while(temp != head) {
18 | P a g e
NoOfElements++;
temp = temp.next; }
if(position < 1 || position > (NoOfElements+1)) {
System.out.print("\nInvalid position.");
} else if (position == 1) {
if(head == null) {
head = newNode;
head.next = head;
} else {
while(temp.next != head) {
temp = temp.next; }
newNode.next = head;
head = newNode;
temp.next = head; }
} else {
temp = head;
for(int i = 1; i < position-1; i++)
temp = temp.next;
newNode.next = temp.next;
temp.next = newNode; } }
void PrintList() {
Node temp = new Node();
temp = this.head;
if(temp != null) {
System.out.print("The list contains: ");
while(true) {
System.out.print(temp.data + " ");
temp = temp.next;
if(temp == this.head)
break; }
System.out.println();
} else {
System.out.println("The list is empty."); } } };
public class circular {
public static void main(String[] args) {

19 | P a g e
LinkedList MyList = new LinkedList();

//Add three elements at the end of the list.


MyList.push_back(25);
MyList.push_back(50);
MyList.push_back(75);
MyList.PrintList();

//Insert an element at position 2


MyList.push_at(100, 2);
MyList.PrintList();

//Insert an element at position 1


MyList.push_at(225, 1);
MyList.PrintList();
}
}

7.2 Output window

8. Program to delete nodes from different positions of Doubly


Circular Linked List.
8.1 Source code

class Node {
int data;
Node next;
20 | P a g e
Node prev; };
class LinkedList {
Node head;
LinkedList(){
head = null; }
void push_back(int newElement) {
Node newNode = new Node();
newNode.data = newElement;
newNode.next = null;
newNode.next = null;
if(head == null) {
head = newNode;
newNode.next = head;
newNode.prev = head;
} else {
Node temp = new Node();
temp = head;
while(temp.next != head)
temp = temp.next;
temp.next = newNode;
newNode.next = head;
newNode.prev = temp;
head.prev = newNode; }
void pop_at(int position) {
Node nodeToDelete = head;
Node temp = head;
int NoOfElements = 0;

if(temp != null) {
NoOfElements++;
temp = temp.next;
}
while(temp != head) {
NoOfElements++;
temp = temp.next; }

21 | P a g e
if(position < 1 || position > NoOfElements) {
System.out.print("\nInvalid position.");
} else if (position == 1) {
if(head.next == head) {
head = null;
} else {
while(temp.next != head)
temp = temp.next;
head = head.next;
temp.next = head;
head.prev = temp;
nodeToDelete = null; }
} else {
temp = head;
for(int i = 1; i < position-1; i++)
temp = temp.next;
nodeToDelete = temp.next;
temp.next = temp.next.next;
temp.next.prev = temp;
nodeToDelete = null; } }
void PrintList() {
Node temp = new Node();
temp = this.head;
if(temp != null) {
System.out.print("The list contains: ");
while(true) {
System.out.print(temp.data + " ");
temp = temp.next;
if(temp == this.head)
break; }
System.out.println();
} else {
System.out.println("The list is empty."); } } };
public class deleteDoublyCircular {
public static void main(String[] args) {

22 | P a g e
LinkedList MyList = new LinkedList();
MyList.push_back(10);
MyList.push_back(20);
MyList.push_back(30);
MyList.push_back(70);
MyList.push_back(50);
MyList.push_back(40);
MyList.PrintList();
MyList.pop_at(3);
MyList.PrintList();
MyList.pop_at(5);
MyList.PrintList();
}
}}

8.2 Output window

9. Program to implement Stack.


9.1 Source code

class MyStack {
private int arr[];
private int top;
private int capacity;
MyStack(int size) {
arr = new int[size];
capacity = size;
top = -1; }
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");
23 | P a g e
System.exit(1); }
System.out.println("Inserting " + x);
arr[++top] = x; }
public int pop() {
if (isEmpty()) {
System.out.println("STACK EMPTY");
System.exit(1); }
return arr[top--]; }
public int getSize() {
return top + 1; }
public Boolean isEmpty() {
return top == -1;
}
public Boolean isFull() {
return top == capacity - 1;
}

public void printStack() {


for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}

public class Stack {


public static void main(String[] args) {
MyStack stack = new MyStack(5);

stack.push(90);
stack.push(60);
stack.push(70);
stack.push(61);
stack.push(32);

24 | P a g e
System.out.print("Stack: ");
stack.printStack();

stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();

}
}}

9.2 Output window

25 | P a g e
10. Program to implement Queue.
10.1 Source code

public class Queue


{
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int currentSize;
public Queue(int size)
{
this.maxSize = size;
this.queueArray = new int[size];
front = 0;
rear = -1;
currentSize = 0; }
public void insert(int item)
{
if(isQueueFull())
{
System.out.println("Queue is full!");
return; }
if(rear == maxSize - 1)
{
rear = -1; }
queueArray[++rear] = item;
currentSize++;
System.out.println("Item added to queue: " + item); }
public int delete()
{
if(isQueueEmpty())
{
throw new RuntimeException("Queue is empty"); }
int temp = queueArray[front++];

26 | P a g e
if(front == maxSize)
{
front = 0; }
currentSize--;
return temp; }
public int peek()
{
return queueArray[front]; }
public boolean isQueueFull()
{
return (maxSize == currentSize);
}
public boolean isQueueEmpty()
{
return (currentSize == 0); }
public static void main(String[] args)
{
Queue queue = new Queue(10);
queue.insert(5);
queue.insert(7);
System.out.println("Item deleted from queue: " + queue.delete());
System.out.println("Item deleted from queue: " + queue.delete());
queue.insert(8);
System.out.println("Item deleted from queue: " + queue.delete()); } }

10.2 Output window

27 | P a g e
11. Program to implement Priority Queue.
11.1 Source code

import java.util.*;

class Priority {

// Main Method
public static void main(String args[])
{

PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

pQueue.add(32);
pQueue.add(512);
pQueue.add(1024);

System.out.println("Peek 1: " + pQueue.peek());


System.out.println("Poll: " + pQueue.poll());
System.out.println("Peek 2: " + pQueue.peek()); }
}

11.2 Output window

12. Program to calculate and display factorial of a number using


recursion.
12.1 Source code

public class Factorial {


static int factorial(int n) {
if (n == 0 || n == 1) {
28 | P a g e
return 1;
} else {
return n * factorial (n - 1);
}
}

public static void main (String[] args) {


int number = 5;

if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}
}

12.2 Output window

29 | P a g e
13. Program to display 7th term of Fibonacci series.
13.1 Source code

class Fibonacci {
public static void main(String[] args) {

int n = 7, firstTerm = 0, secondTerm = 1;


System.out.println("Fibonacci Series till " + n + " terms:");

for (int i = 1; i <= n; ++i) {


System.out.print(firstTerm + ", ");

int nextTerm = firstTerm + secondTerm;


firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

13.2 Output window

30 | P a g e
14. Program to calculate product of two integer.
14.1 Source code

import java.util.Scanner;

public class Product {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);

System.out.print("Input first number: ");


int num1 = in.nextInt();

System.out.print("Input second number: ");


int num2 = in.nextInt();

System.out.println(num1 + " x " + num2 + " = " + num1 * num2);


}

14.2 Output window

15. Program to implement Tower of Hanoi problem with 5 disks.


15.1 Source Code

public class TowerOfHanoi {

31 | P a g e
static void towerOfHanoi(int n, char source, char destination, char auxiliary) {
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + destination);
return;
}
towerOfHanoi(n - 1, source, auxiliary, destination);
System.out.println("Move disk " + n + " from " + source + " to " + destination);
towerOfHanoi(n - 1, auxiliary, destination, source);
}

public static void main(String[] args) {


int numDiscs = 5;

System.out.println("Tower of Hanoi steps:");


towerOfHanoi(numDiscs, 'A', 'C', 'B');
}
}

32 | P a g e
15.2 Output window

16. Program to implement binary tree using linked list.


16.1 Source Code

import java.util.Scanner;

33 | P a g e
class Node
{
Node left, right;
int data;
public Node(int n)
{
left = null;
right = null;
data = n;
}
}
class BST
{
private Node root;
public BST()
{
root = null;
}
public void insert(int data)
{
root = insert(root, data);
}
private Node insert(Node node, int data)
{
if (node == null)
node = new Node(data);
else
{
if (data <= node.data)
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}

34 | P a g e
public void inorder()
{
inorder(root);
}
private void inorder(Node r)
{
if (r != null)
{
inorder(r.left);
System.out.print(r.data +" ");
inorder(r.right);
}
}
public void preorder()
{
preorder(root);
}
private void preorder(Node r)
{
if (r != null)
{
System.out.print(r.data +" ");
preorder(r.left);
preorder(r.right);
}
}
public void postorder()
{
postorder(root);
}
private void postorder(Node r)
{
if (r != null)
{
postorder(r.left);

35 | P a g e
postorder(r.right);
System.out.print(r.data +" ");
} } }
public class BinaryTreeLinkedlist
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
BST bst = new BST();
System.out.println("Linked List Binary Search Tree Test\n");
char ch;
do
{
System.out.println("Enter integer element to insert");
bst.insert( scan.nextInt() );
System.out.print("\nPost order : ");
bst.postorder();
System.out.print("\nPre order : ");
bst.preorder();
System.out.print("\nIn order : ");
bst.inorder();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y'); } }

36 | P a g e
16.2 Output window

17. Program to implement Depth first traversal of Binary tree.


17.1 Source code

node and key value*/


class Node {
37 | P a g e
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null; } }
class BinaryTree {
Node root;
BinaryTree() { root = null; }
void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.key + " ");
printInorder(node.right); }
void printInorder() { printInorder(root); }
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("\nIn-order traversal :");
tree.printInorder(); } }

38 | P a g e
17.2 Output window

18. Program to implement Dijkstra’s Algorithm.


18.1 Source code

import java.io.*;

39 | P a g e
import java.util.*;
public class Dijkstra {
public static void main(String[] args) {
int adjMat [] [] = {
{0, 2, 0, 4, 0, 0},
{0, 0, 3, 2, 0, 0},
{2, 0, 0, 0, 0, 4},
{0, 0, 0, 0, 2, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0}};

int [] distance = new int[adjMat.length];


int source = 1;
boolean [] visited = new boolean[adjMat.length];
distance[source] = 0;

for (int i = 0; i < adjMat.length; i++) {


if( i == source) continue;
distance[i] = Integer.MAX_VALUE;
}

for(int i = 0; i < adjMat.length; i++) {


int minDistVertex = findMinDistVertex(distance, visited);

visited[minDistVertex] = true;
for(int j = 0; j < adjMat.length; j++) {
if(adjMat[minDistVertex][j] != 0 && visited[j] == false
&& distance[minDistVertex] != Integer.MAX_VALUE) {
int newDist = distance[minDistVertex] +
adjMat[minDistVertex][j];
if(newDist < distance[j]) {
distance[j] = newDist;
} } } }
for(int i = 0; i < adjMat.length; i++) {
System.out.println("Vertex : " + i + " & Distance from Source :
" +distance[i]); } }

40 | P a g e
public static int findMinDistVertex(int[] distance, boolean [] visited) {

int minVertex = -1;

for(int i = 0; i < distance.length; i++) {


if(visited[i] == false && (minVertex == -1 || distance[i] <
distance[minVertex])) {
minVertex = i;
}
}
return minVertex;
}
}

18.1 Output window

19. Program to implement Kruskal’s Algorithm.


19.1 Source Code

import java.util.*;
class Graph {
class Edge implements Comparable<Edge> {
int src, dest, weight;
public int compareTo(Edge compareEdge) {
return this.weight - compareEdge.weight; } };
class subset {
41 | P a g e
int parent, rank; };
int vertices, edges;
Edge edge[];
Graph(int v, int e) {
vertices = v;
edges = e;
edge = new Edge[edges];
for (int i = 0; i < e; ++i)
edge[i] = new Edge(); }
int find(subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent; }
void Union(subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++; } }
void KruskalAlgo() {
Edge result[] = new Edge[vertices];
int e = 0;
int i = 0;
for (i = 0; i < vertices; ++i)
result[i] = new Edge();
Arrays.sort(edge);
subset subsets[] = new subset[vertices];
for (i = 0; i < vertices; ++i)
subsets[i] = new subset();
for (int v = 0; v < vertices; ++v) {
subsets[v].parent = v;

42 | P a g e
subsets[v].rank = 0; }
i = 0;
while (e < vertices - 1) {
Edge next_edge = new Edge();
next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y); } }
for (i = 0; i < e; ++i)
System.out.println(result[i].src + " - " + result[i].dest + ": " + result[i].weight);
}
public static void main(String[] args) {
int vertices = 6;
int edges = 8;
Graph G = new Graph(vertices, edges);
G.edge[0].src = 0;
G.edge[0].dest = 1;
G.edge[0].weight = 4;

G.edge[1].src = 0;
G.edge[1].dest = 2;
G.edge[1].weight = 4;

G.edge[2].src = 1;
G.edge[2].dest = 2;
G.edge[2].weight = 2;

G.edge[3].src = 2;
G.edge[3].dest = 3;
G.edge[3].weight = 3;

G.edge[4].src = 2;
G.edge[4].dest = 5;

43 | P a g e
G.edge[4].weight = 2;

G.edge[5].src = 2;
G.edge[5].dest = 4;
G.edge[5].weight = 4;

G.edge[6].src = 3;
G.edge[6].dest = 4;
G.edge[6].weight = 3;

G.edge[7].src = 5;
G.edge[7].dest = 4;
G.edge[7].weight = 3;
G.KruskalAlgo(); }
}

19.2 Output window

20. Programs to implement Merge sorting algorithm


20.1 Source code

public class MergeSort {

static void merge(int arr[], int l, int m, int r) {

int n1 = m - l + 1;
int n2 = r - m;

int L[] = new int[n1];


int R[] = new int[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];

44 | P a g e
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
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++;
}
}

static void mergeSort(int arr[], int l, int r) {


if (l < r) {

int m = l + (r - l) / 2;

45 | P a g e
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

public static void main(String args[]) {


int arr[] = { 10, 9, 13, 25, 1000, 12 };
int arrSize = arr.length;

System.out.println("Given array:");
for (int num : arr) {
System.out.print(num + " ");
}

mergeSort(arr, 0, arrSize - 1);

System.out.println("\nSorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

20.2 Output window

46 | P a g e
21. Programs to implement Radix sorting algorithm
21.1 Source code

import java.util.Arrays;
class RadixSort {
void countingSort(int array[], int size, int place) {
int[] output = new int[size + 1];
int max = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > max)
max = array[i];
}
int[] count = new int[max + 1];
for (int i = 0; i < max; ++i)
count[i] = 0;
for (int i = 0; i < size; i++)
count[(array[i] / place) % 10]++;
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
for (int i = size - 1; i >= 0; i--) {
output[count[(array[i] / place) % 10] - 1] = array[i];
count[(array[i] / place) % 10]--;
}
for (int i = 0; i < size; i++)
array[i] = output[i];
}
int getMax(int array[], int n) {
int max = array[0];
for (int i = 1; i < n; i++)
if (array[i] > max)
max = array[i];
return max;
}
void radixSort(int array[], int size) {

47 | P a g e
int max = getMax(array, size);

for (int place = 1; max / place > 0; place *= 10)


countingSort(array, size, place);
}
public static void main(String args[]) {
int[] data = { 121, 432, 60, 56, 3, 45, 726 };
int size = data.length;
RadixSort rs = new RadixSort();
rs.radixSort(data, size);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}

21.2 Output window

22. Programs to implement Heap sorting algorithm


22.1 Source code

public class HeapSort {


public void sort(int arr[]) {
int n = arr.length;

48 | P a g e
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

heapify(arr, i, 0); } }
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);
}
}

static void printArray(int arr[]) {


int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

public static void main(String args[]) {


int arr[] = { 20, 12, 130, 122342, 1222,909 };

49 | P a g e
HeapSort hs = new HeapSort();
hs.sort(arr);

System.out.println("Sorted array is");


printArray(arr);
}
}

22.2 Output window

23. Program to implement Linear Probing.


23.1 Source code

class HashTable {
private int[] table;
private int size;

50 | P a g e
public HashTable(int size) {
this.size = size;
table = new int[size];
for (int i = 0; i < size; i++) {
table[i] = -1; // Initialize all slots as unoccupied (-1)
}
}

// Hash function
private int hash(int key) {
return key % size;
}

// Insert key into the hash table


public void insert(int key) {
int index = hash(key);

// Linear probing
while (table[index] != -1) {
index = (index + 1) % size;
}

table[index] = key;
}

// Display the hash table


public void display() {
for (int i = 0; i < size; i++) {
System.out.println(i + ": " + table[i]);
}
}
}

public class LinearProbingExample {

51 | P a g e
public static void main(String[] args) {
HashTable hashTable = new HashTable(10);

int[] keys = { 23, 45, 67, 89, 12, 34, 56, 78, 90, 21 };

for (int key : keys) {


hashTable.insert(key);
}

System.out.println("Hash Table with Linear Probing:");


hashTable.display();
}
}

23.2 Output window

52 | P a g e

You might also like