M Tech Advanced Algorithm
M Tech Advanced Algorithm
NO
. EXPERIMENT PAGE
Write Java programs that use both recursive and non-recursive functions for
implementing the following searching methods: a) Linear search b) Binary
1 search 2-3
Write a Java program to implement all the functions of a dictionary (ADT)
using hashing.
2 4
Write a Java program to implement Dijkstra’s algorithm for Single source
shortest path problem.
3 5-6
Write Java programs that use recursive and non-recursive functions to traverse
the given binary tree in a) Preorder b) Inorder c) Postorder.
4 7-9
Write Java programs for the implementation of bfs and dfs for a given graph.
5 10-11
Write Java programs for implementing the following sorting methods: a) Bubble
sort b) Insertion sort c) Quick sort d) Merge sort e) Heap sort f) Radix sort g)
6 Binary tree sort 12-17
Write a Java program to perform the following operations: a) Insertion into a B-
tree b) Searching in a B-tree
7 18-21
Write a Java program that implements Kruskal’s algorithm to generate
minimum cost spanning tree.
8 22-24
Write a Java program that implements KMP algorithm for pattern matching.
9 25-26
1
Experiment 1: Linear and Binary Search (Recursive and Non-Recursive)
Objective: To implement recursive and non-recursive functions for Linear Search and
Binary Search.
Program:
import java.util.*;
class Experiment1
{
// Non-recursive Linear Search
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key)
return i;
}
return -1;
}
// Recursive Linear Search
public static int linearSearchRec(int[] arr, int key, int index) {
if (index >= arr.length)
return -1;
if (arr[index] == key)
return index;
return linearSearchRec(arr, key, index + 1);
}
// Non-recursive Binary Search
public static int binarySearch(int[] arr, int key) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
// Recursive Binary Search
public static int binarySearchRec(int[] arr, int key, int low, int high) {
if (low > high)
return -1;
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
return binarySearchRec(arr, key, mid + 1, high);
else
return binarySearchRec(arr, key, low, mid - 1);
}
public static void main(String[] args) {
2
int[] arr = {2, 4, 6, 8, 10, 12, 14};
int key = 10;
3
Experiment 2: Dictionary using Hashing
Objective: To implement all the functions of a dictionary (ADT) using Hashing.
Program:
import java.util.HashMap;
class Experiment2 {
public static void main(String[] args) {
HashMap<String, String> dictionary = new HashMap<>();
// Insert
dictionary.put("Java", "A high-level programming language.");
dictionary.put("Python", "An interpreted high-level programming language.");
// Search
String word = "Java";
if (dictionary.containsKey(word)) {
System.out.println(word + ": " + dictionary.get(word));
} else {
System.out.println(word + " not found in dictionary.");
}
// Delete
dictionary.remove("Python");
// Display all
for (Map.Entry<String, String> entry : dictionary.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
4
Experiment 3: Dijkstra’s Algorithm
Objective: To implement Dijkstra’s algorithm to find the shortest path from a single
source vertex to all other vertices in a given weighted graph.
Program:
import java.util.*;
printSolution(dist, src);
}
5
// A utility function to print the constructed distance array
static void printSolution(int[] dist, int src) {
System.out.println("Vertex\tDistance from Source " + src);
for (int i = 0; i < dist.length; i++)
System.out.println(i + "\t\t" + dist[i]);
}
// Main method
public static void main(String[] args) {
int[][] graph = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
6
Experiment 4: Binary Tree Traversal (Recursive and Non-Recursive)
Objective: To write Java programs that use both recursive and non-recursive methods
to traverse a given binary tree in: a) Preorder b) Inorder c) Postorder
Program:
import java.util.*;
// Node class
class TreeNode {
int data;
TreeNode left, right;
TreeNode(int item) {
data = item;
left = right = null;
}
}
TreeNode root;
7
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
System.out.print(current.data + " ");
current = current.right;
}
}
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
System.out.print(temp.data + " ");
if (temp.right != null)
stack.push(temp.right);
if (temp.left != null)
stack.push(temp.left);
}
}
stack1.push(node);
while (!stack1.isEmpty()) {
TreeNode temp = stack1.pop();
stack2.push(temp);
if (temp.left != null)
stack1.push(temp.left);
if (temp.right != null)
stack1.push(temp.right);
}
while (!stack2.isEmpty()) {
System.out.print(stack2.pop().data + " ");
}
}
8
public static void main(String[] args) {
BinaryTreeTraversal tree = new BinaryTreeTraversal();
System.out.println(\"Recursive Inorder:\");
tree.inorderRecursive(tree.root);
System.out.println(\"\\nNon-Recursive Inorder:\");
tree.inorderNonRecursive(tree.root);
System.out.println(\"\\n\\nRecursive Preorder:\");
tree.preorderRecursive(tree.root);
System.out.println(\"\\nNon-Recursive Preorder:\");
tree.preorderNonRecursive(tree.root);
System.out.println(\"\\n\\nRecursive Postorder:\");
tree.postorderRecursive(tree.root);
System.out.println(\"\\nNon-Recursive Postorder:\");
tree.postorderNonRecursive(tree.root);
}
}
9
Experiment 5: BFS and DFS for a Graph
Objective:
To implement Breadth-First Search (BFS) and Depth-First Search (DFS) traversal
algorithms for a given graph using Java.
Program:
import java.util.*;
// Constructor
public GraphTraversal(int v) {
vertices = v;
adjList = new LinkedList[v];
for (int i = 0; i < v; i++) {
adjList[i] = new LinkedList<>();
}
}
visited[start] = true;
queue.add(start);
10
// ----------- DFS Implementation -----------
void DFSUtil(int node, boolean[] visited) {
visited[node] = true;
System.out.print(node + " ");
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 5);
11
Experiment 6: Sorting Algorithms
Objective: To implement various sorting algorithms in Java.
a) Bubble Sort
import java.util.Arrays;
class BubbleSort {
// Bubble Sort
public static 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
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped)
break;
}
}
class InsertionSort {
// Insertion Sort
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
12
public static void main(String[] args) {
int[] arr = {9, 5, 1, 4, 3};
insertionSort(arr);
System.out.println("Sorted array (Insertion Sort): " + Arrays.toString(arr));
}
}
c) Quick Sort
import java.util.*;
class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
class MergeSort {
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
13
merge(arr, left, mid, right);
}
}
public static void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] L = new int[n1];
int[] R = new int[n2];
System.arraycopy(arr, left, L, 0, n1);
System.arraycopy(arr, mid + 1, R, 0, n2);
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}
while (i < n1)
arr[k++] = L[i++];
while (j < n2)
arr[k++] = R[j++];
}
class HeapSort {
public static void heapSort(int[] arr) {
int n = arr.length;
heapify(arr, i, 0);
}
}
14
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
class RadixSort {
public static void radixSort(int[] arr) {
int max = getMax(arr);
for (int exp = 1; max / exp > 0; exp *= 10)
countSort(arr, exp);
}
15
count[(i / exp) % 10]++;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int item) {
val = item;
left = right = null;
}
}
class BinaryTreeSort {
TreeNode root;
16
return root;
}
17
Experiment 7: B-Tree Operations
Objective: To implement insertion and search operations in a B-tree.
Program:
// BTreeNode class
class BTreeNode {
int[] keys; // An array of keys
int t; // Minimum degree (defines the range for number of keys)
BTreeNode[] children; // An array of child pointers
int n; // Current number of keys
boolean leaf; // Is true when node is leaf. Otherwise false
if (!leaf) {
children[i].traverse();
}
}
if (leaf) {
return null;
}
return children[i].search(key);
18
}
// Insert a new key in the subtree rooted with this node (assuming this node is not full)
void insertNonFull(int key) {
int i = n - 1;
if (leaf) {
// Move keys greater than key forward
while (i >= 0 && keys[i] > key) {
keys[i + 1] = keys[i];
i--;
}
keys[i + 1] = key;
n = n + 1;
} else {
while (i >= 0 && keys[i] > key) {
i--;
}
if (children[i + 1].n == 2 * t - 1) {
splitChild(i + 1, children[i + 1]);
if (!y.leaf) {
for (int j = 0; j < t; j++) {
z.children[j] = y.children[j + t];
}
}
y.n = t - 1;
19
}
children[i + 1] = z;
// BTree class
class BTree {
BTreeNode root;
int t; // Minimum degree
BTree(int t) {
this.root = null;
this.t = t;
}
// Insertion function
void insert(int key) {
if (root == null) {
root = new BTreeNode(t, true);
root.keys[0] = key;
root.n = 1;
} else {
if (root.n == 2 * t - 1) {
BTreeNode s = new BTreeNode(t, false);
s.children[0] = root;
s.splitChild(0, root);
int i = 0;
if (s.keys[0] < key) {
i++;
20
}
s.children[i].insertNonFull(key);
root = s;
} else {
root.insertNonFull(key);
}
}
}
}
// Driver class
public class BTreeDemo {
public static void main(String[] args) {
BTree t = new BTree(3); // A B-Tree with minimum degree 3
int k = 6;
if (t.search(k) != null)
System.out.println("\n\nPresent");
else
System.out.println("\n\nNot Present");
}
}
21
Experiment 8: Write a Java program that implements Kruskal’s algorithm to generate
minimum cost spanning tree.
Objective: To implement graph algorithms for Minimum cost Spanning tree.
Program:
import java.util.*;
DisjointSet(int n) {
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; ++i)
parent[i] = i;
}
22
parent[yroot] = xroot;
rank[xroot]++;
}
}
}
KruskalMST(int v, int e) {
V = v;
E = e;
edges = new Edge[E];
}
void kruskalMST() {
// Step 1: Sort edges by increasing weight
Arrays.sort(edges);
Edge[] result = new Edge[V - 1]; // MST will have V-1 edges
int e = 0, i = 0; // Index for result[] and sorted edges
int x = ds.find(next.src);
int y = ds.find(next.dest);
23
// Driver method
public static void main(String[] args) {
// Add edges
graph.edges[0] = new Edge(0, 1, 10);
graph.edges[1] = new Edge(0, 2, 6);
graph.edges[2] = new Edge(0, 3, 5);
graph.edges[3] = new Edge(1, 3, 15);
graph.edges[4] = new Edge(2, 3, 4);
24
Experiment 9: Write a Java program that implements KMP algorithm for pattern
matching.
Objective: To implement KMP algorithm.
Program:
public class KMPAlgorithm {
while (i < N) {
if (pattern.charAt(j) == text.charAt(i)) {
i++;
j++;
}
if (j == M) {
System.out.println("Pattern found at index " + (i - j));
j = lps[j - 1]; // continue searching
} else if (i < N && pattern.charAt(j) != text.charAt(i)) {
25
if (j != 0) {
j = lps[j - 1]; // use LPS to skip characters
} else {
i++;
}
}
}
}
// Driver method
public static void main(String[] args) {
KMPAlgorithm kmp = new KMPAlgorithm();
kmp.KMPSearch(pattern, text);
}
}
26