ADSA Lab Record (CP 4161)
ADSA Lab Record (CP 4161)
Aim:
To create a java program for the implementation of recursive function for tree
traversal and Fibonacci.
Algorithm:
2. Design the first thread that generates a random integer for every 1 second .
3. If the first thread value is even, design the second thread as the square of the number
and then print it.
4.If the first thread value is odd, then third thread will print the value of cube of
the number.
PROGRAM CODING :
double mun;
try
cubeThread.start();
for(i=0;i<10;i++)
{
System.out.println(“t1-”+i);
if(i%2==0)
sqt.setNum(new Double(i));
else
Thread. sleep(1000);
catch(InterruptedException e)
e.printStackTrace();
Double num;
try
int i=0;
do{
i++;
System.out.println(“t2->square of “+num+”=”+(num*num));
num = null;
Thread.sleep(1000);
}while(i<=5);
catch (Exception e)
e.printStackTrace();
return num;
this.num = num;
Double num;
public void run()
try {
int i=0;
do{
i++;
System.out.println(“t3-->Cube of “+num+”=”+(num*num*num));
num=null;
Thread.sleep(1000);
while(i<=5);
catch (Exception e)
e.printStackTrace();
return num;
this.num = num;
}
OUTPUT :
Result :
Thus the program for the implementation of recursive function for tree traversal and
Fibonacci is created and the output is verified successfully.
Ex no: 2 IMPLEMENTATION OF ITERATIVE FUNCTION FOR TREE
TRAVERSAL AND FIBONACCI.
Aim:
To create a java program for the implementation of iterative function for tree traversal
and Fibonacci.
Algorithm:
2. Design the first thread that generates a random integer for every 1 second .
3. If the first thread value is even, design the second thread as the square of the number
and then print it.
4. If the first thread value is odd, then third thread will print the value of cube of
the number.
PROGRAM CODING:
import java.io.*;
else if (fName.endsWith(“.exe"))
else if(fName.endsWith(".txt"))
else
}
}
OUTPUT :
Result :
Thus the program for the implementation of iterative function for tree traversal and
Fibonacci is created and the output is verified successfully.
AIM:
ALGORITHM:
1. If the list has only one element, return the list and terminate.
2. Split the list into two halves that are as equal in length as possible
3. Using recursion, sort both lists using merge sort.
4. Merge the two sorted lists and return the result.
5. Stop the program.
PROGRAM CODING:
import java.util.Scanner;
{
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
Result:
Thus the program for the implementation of Merge sort is created and the output is
verified successfully.
AIM:
ALGORTIHM:
1. Choose an element, called pivot, from the list. Generally pivot can be the middle index
2. Reorder the list so that all elements with values less than the pivot come before the pivot
3. All elements with values greater than the pivot come after it (equal values can go either way).
After this partitioning, the pivot is in its final position. This is called the partition operation.
4. Recursively apply the above steps to the sub-list of elements with smaller values and separately the
sub-list of elements with greater values.
PROGRAM CODING:
import java.util.Scanner;
if (N <= 1)
return;
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
a[low + k] = temp[k];
int n, i;
n = scan.nextInt();
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
System.out.print(arr[i]+" ");
System.out.println();
}
Result:
Thus the program for the implementation of Quick sort is created and the output is
verified successfully.
Ex no:4 IMPLEMENTATION OF BINARY SEARCH TREE
AIM:
ALGORITHM:
2. Compare, the search element with the value of root node in the tree.
3. If both are matching, then display "Given node found!!!" and terminate the function
4. If both are not matching, then check whether search element is smaller or larger
5. If search element is smaller, then continue the search process in left subtree.
6. If search element is larger, then continue the search process in right subtree.
7. Repeat the same until we found exact element or we completed with a leaf node
8. If we reach to the node with search value, then display "Element is found" and terminate
9. If we reach to a leaf node and it is also not matching, then display "Element not found" and
terminate the function.
PROGRAM CODING:
public BinarySearchTree()
this.root = null;
while(current!=null)
if(current.data==id)
return true;
else if(current.data>id)
current = current.left;
Else
current = current.right;
return false;
while(current.data!=id)
parent = current;
if(current.data>id)
{
isLeftChild = true;
current = current.left;
Else
isLeftChild = false;
current = current.right;
if(current ==null)
return false;
if(current==root)
root = null;
if(isLeftChild ==true)
parent.left = null;
Else
{
parent.right = null;
else if(current.right==null)
if(current==root)
root = current.left;
else if(isLeftChild)
parent.left = current.left;
Else
parent.right = current.left;
else if(current.left==null)
if(current==root)
root = current.right;
else if(isLeftChild)
parent.left = current.right;
}
Else
parent.right = current.right;
//now we have found the minimum element in the right sub tree
if(current==root)
root = successor;
else if(isLeftChild)
parent.left = successor;
Else
parent.right = successor;
successor.left = current.left;
return true;
while(current!=null)
successsorParent = successsor;
successsor = current;
current = current.left;
//check if successor has the right child, it cannot have left child for sure
// successsorParent
if(successsor!=deleleNode.right)
successsorParent.left = successsor.right;
successsor.right = deleleNode.right;
return successsor;
if(root==null)
root = newNode;
return;
}
Node current = root;
while(true)
parent = current;
if(id<current.data)
current = current.left;
if(current==null)
parent.left = newNode;
return;
Else
current = current.right;
if(current==null)
parent.right = newNode;
return;
if(root!=null)
{
display(root.left);
display(root.right);
b.insert(3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
b.display(b.root);
System.out.println("");
b.display(root);
b.display(root);
b.display(root);
class Node
int data;
Node left;
Node right;
this.data = data;
left = null;
right = null;
}
OUTPUT
Result:
Thus the program for the implementation of binary search tree is created and the
output is verified successfully.
Ex no: 5 RED-BLACK TREE IMPLEMENTATION
AIM:
ALGORITHM:
2. If tree is Empty then insert the new Node as Root node with colour Black and exit from the
operation.
3. If tree is not Empty then insert the new Node as a leaf node with Red colour.
4. If the parent of new Node is Black then exit from the operation.
5. If the parent of new Node is Red then check the colour of parent node's sibling of new Node.
6. If it is Black or NULL node then make a suitable Rotation and Recolor it.
7. If it is Red colour node then perform Recolor and Recheck it. Repeat the same until tree becomes
Red Black Tree.
PROGRAM CODING:
import java.util.Scanner;
class RedBlackNode
int element;
int color;
{
left = lt;
right = rt;
element = theElement;
color = 1;
class RBTree
static
nullNode.left = nullNode;
nullNode.right = nullNode;
header.left = nullNode;
header.right = nullNode;
}
public boolean isEmpty()
header.right = nullNode;
nullNode.element = item;
great = grand;
grand = parent;
parent = current;
handleReorient( item );
if (current != nullNode)
return;
parent.left = current;
else
parent.right = current;
handleReorient( item );
current.color = RED;
current.left.color = BLACK;
current.right.color = BLACK;
if (parent.color == RED)
grand.color = RED;
current.color = BLACK;
header.right.color = BLACK;
else
RedBlackNode k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
RedBlackNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
return countNodes(header.right);
if (r == nullNode)
return 0;
else
int l = 1;
l += countNodes(r.left);
l += countNodes(r.right);
return l;
r = r.left;
r = r.right;
else
found = true;
break;
return found;
inorder(header.right);
{
if (r != nullNode)
inorder(r.left);
char c = 'B';
if (r.color == 0)
c = 'R';
inorder(r.right);
preorder(header.right);
if (r != nullNode)
char c = 'B';
if (r.color == 0)
c = 'R';
preorder(r.left);
preorder(r.right);
{
postorder(header.right);
if (r != nullNode)
postorder(r.left);
postorder(r.right);
char c = 'B';
if (r.color == 0)
c = 'R';
char ch;
do
switch (choice)
case 1 :
rbt.insert( scan.nextInt() );
break;
case 2 :
break;
case 3 :
break;
case 4 :
break;
case 5 :
System.out.println("\nTree Cleared");
rbt.makeEmpty();
break;
default :
break;
}
rbt.postorder();
rbt.preorder();
rbt.inorder();
ch = scan.next().charAt(0);
}
OUTPUT :
Result:
Thus the program for the implementation of Red black tree is created and the output is
verified successfully.
Ex no:6 HEAP IMPLEMENTATION
AIM:
ALGORITHM:
1.Call the build Max Heap() function on the list. Also referred to as heapify(), this builds a
heap from a list in O(n) operations.
2.Swap the first element of the list with the final element. Decrease the considered range of
the list by one.
3.Call the shift Down() function on the list to sift the new first element to its appropriate
index in the heap.
4.Go to step (2) unless the considered range of the list is one element.
5.The build Max Heap() operation is run once, and is O(n) in performance. the shift Down()
function is O(log n), and is called n times. Therefore, the performance of this algorithm is
O(n + n log n) = O(n log n).
PROGRAM CODING :
import java.util.Scanner;
class Heap
maxSize = mx;
heapSize = 0;
}
public boolean isEmpty()
return heapSize == 0;
if (heapSize + 1 == maxSize)
return false;
heapArray[++heapSize] = ele;
heapArray[pos] = heapArray[pos/2];
pos /=2;
heapArray[pos] = ele;
return true;
if (isEmpty() )
item = heapArray[1];
temp = heapArray[heapSize--];
parent = 1;
child = 2;
while (child <= heapSize)
child++;
break;
heapArray[parent] = heapArray[child];
parent = child;
child *= 2;
heapArray[parent] = temp;
return item;
System.out.println("\n");
System.out.println("Heap Test\n\n");
char ch;
do
System.out.println("\nHeap Operations\n");
boolean chk;
switch (choice)
case 1 :
if (chk)
System.out.println("Insertion successful\n");
else
System.out.println("Insertion failed\n");
break;
case 2 :
if (!h.isEmpty())
h.remove();
else
break;
case 3 :
System.out.println("Empty status = "+ h.isEmpty());
break;
default :
break;
h.displayHeap();
ch = scan.next().charAt(0);
}
OUTPUT:
Result:
Thus the program for the implementation of Heap is created and the output is verified
successfully.
Ex no:7 FIBONACCI HEAP IMPLEMENTATION
AIM:
ALGORITHM:
PROGRAM CODING :
importjava.util.*;
classFibonacciHeapNode
{
FibonacciHeapNode child, left, right, parent;
int element;
publicFibonacciHeapNode(int element)
{
this.right = this;
this.left = this;
this.element = element;
}
}
classFibonacciHeap
{
privateFibonacciHeapNode root;
privateint count;
publicFibonacciHeap()
{
root = null;
count = 0;
}
publicbooleanisEmpty()
{
return root == null;
}
public void clear()
{
root = null;
count = 0;
}
public void insert(int element)
{
FibonacciHeapNode node = new FibonacciHeapNode(element);
node.element = element;
if (root != null)
{
node.left = root;
node.right = root.right;
root.right = node;
node.right.left = node;
if (element <root.element)
root = node;
}
else
root = node;
count++;
}
public void display()
{
System.out.print("\nHeap = ");
FibonacciHeapNodeptr = root;
if (ptr == null)
{
System.out.print("Empty\n");
return;
}
do
{
System.out.print(ptr.element +" ");
ptr = ptr.right;
} while (ptr != root &&ptr.right != null);
System.out.println();
}
}
public class FibonacciHeapTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("FibonacciHeap Test\n\n");
FibonacciHeapfh = new FibonacciHeap();
charch;
do
{
System.out.println("\nFibonacciHeap Operations\n");
System.out.println("1. insert element ");
System.out.println("2. check empty");
System.out.println("3. clear");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter element");
fh.insert(scan.nextInt() );
break;
case 2 :
System.out.println("Empty status = "+ fh.isEmpty());
break;
case 3 :
fh.clear();
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
fh.display();
System.out.println("\nDo you want to continue (Type y or n)\n");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
OUTPUT:
Result:
Thus the program for the implementation of Fibonacci heap implementation is created
and the output is verified successfully.
AIM:
To write a java program to implement Graph Traversals using Depth First Search tree algorithm.
ALGORITHM:
4. If we see an adjacent node that has not been ‘visited’, add it to the stack.
5. Then pop of the top node on the stack and traverse to it.
PROGRAM CODING:
package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
int data;
boolean visited;
List<Node> neighbours;
Node(int data)
{
this.data=data;
this.neighbours=new ArrayList<>();
this.neighbours.add(neighbourNode);
return neighbours;
this.neighbours = neighbours;
// Recursive DFS
List<Node> neighbours=node.getNeighbours();
Node n=neighbours.get(i);
dfs(n);
n.visited=true;
}
stack.add(node);
node.visited=true;
while (!stack.isEmpty())
Node element=stack.pop();
List<Node> neighbours=element.getNeighbours();
Node n=neighbours.get(i);
stack.add(n);
n.visited=true;
node40.addneighbours(node10);
node40.addneighbours(node20);
node10.addneighbours(node30);
node20.addneighbours(node10);
node20.addneighbours(node30);
node20.addneighbours(node60);
node20.addneighbours(node50);
node30.addneighbours(node60);
node60.addneighbours(node70);
node50.addneighbours(node70);
dfsExample.dfsUsingStack(node40);
System.out.println();
node40.visited=false;
node10.visited=false;
node20.visited=false;
node30.visited=false;
node60.visited=false;
node50.visited=false;
node70.visited=false;
System.out.println("The DFS traversal of the graph using recursion ");
dfsExample.dfs(node40);
OUTPUT :
Result:
Thus the program for the implementation of Graph traversal heap implementation is
created and the output is verified successfully.
AIM:
ALGORITHM:
1. Create a graph F (a set of trees), where each vertex in the graph is a separate tree.
5. If the removed edge connects two different trees then add it to the forest F, combining two treess
into a single tree.
PROGRAM CODING:
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
this.numberOfVertices = numberOfVertices;
edge.sourcevertex = source;
edge.destinationvertex = destination;
edge.weight = adjacencyMatrix[source][destination];
adjacencyMatrix[destination][source] = MAX_VALUE;
edges.add(edge);
spanning_tree[edge.sourcevertex][edge.destinationvertex] = edge.weight;
spanning_tree[edge.destinationvertex][edge.sourcevertex] = edge.weight;
if (checkCycle.checkCycle(spanning_tree, edge.sourcevertex))
spanning_tree[edge.sourcevertex][edge.destinationvertex] = 0;
spanning_tree[edge.destinationvertex][edge.sourcevertex] = 0;
edge.weight = -1;
continue;
visited[edge.sourcevertex] = 1;
visited[edge.destinationvertex] = 1;
if (visited[i] == 0)
finished = false;
break;
} else
finished = true;
if (finished)
break;
System.out.println();
System.out.print(source + "\t");
System.out.print(spanning_tree[source][destination] + "\t");
System.out.println();
int adjacency_matrix[][];
int number_of_vertices;
number_of_vertices = scan.nextInt();
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
if (adjacency_matrix[i][j] == 0)
adjacency_matrix[i][j] = MAX_VALUE;
kruskalAlgorithm.kruskalAlgorithm(adjacency_matrix);
scan.close();
class Edge
int sourcevertex;
int destinationvertex;
int weight;
Override
return -1;
return 0;
class CheckCycle
public CheckCycle()
adjacencyMatrix[sourcevertex][destinationvertex] = adjacency_matrix[sourcevertex]
[destinationvertex];
int i = source;
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
element = stack.peek();
i = element;
if (stack.contains(i))
cyclepresent = true;
return cyclepresent;
stack.push(i);
visited[i] = 1;
adjacencyMatrix[i][element] = 0;
element = i;
i = 1;
continue;
i++;
}
stack.pop();
return cyclepresent;
Result:
Thus the program for the implementation of spanning tree is created and the output is
verified successfully.
To write a java program for the implementation of Dijkstra’s Algorithm Using Shortest Path.
ALGORITHM:
1. Initialization of all nodes with distance "infinite"; initialization of the starting node with 0
2. Marking of the distance of the starting node as permanent, all other distances as temporarily.
4. Calculation of the temporary distances of all neighbour nodes of the active node by summing
distance with the weights of the edges.
5. If such a calculated distance of a node is smaller as the current one, update the distance and set the
current node as antecessor. This step is also called update and is Dijkstra's central idea.
6. Setting of the node with the minimal temporary distance as active. Mark its distance as permanent.
Repeating of steps 4 to 7 until there aren't any nodes left with a permanent distance, which neighbours
still have temporary distance
PROGRAM CODING:
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
this.number_of_nodes = number_of_nodes;
int evaluationNode;
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
distances[i] = Integer.MAX_VALUE;
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
int min ;
int node = 0;
node = iterator.next();
min = distances[node];
if (unsettled.contains(i))
min = distances[i];
node = i;
return node;
{
if (!settled.contains(destinationNode))
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE)
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
distances[destinationNode] = newDistance;
unsettled.add(destinationNode);
}}}}
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
try
number_of_vertices = scan.nextInt();
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
adjacency_matrix[i][j] = 0;
continue;
if (adjacency_matrix[i][j] == 0)
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}}}
source = scan.nextInt();
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
scan.close();
}
Result:
Thus the program for the implementation of Dijkstra’s algorithm is created and the
output is verified successfully.
AIM:
To write a java program for the implementation of Bellman Ford Algorithm by using the concept
Shortest Path.
ALGORITHM:
2. Choose the starting vertex and assign infinity path values to all other vertex.
3. Visit each edge and relax the path distance if they are inaccurate.
4. We need to do this V times because in the worst case the vertex path length might need to be read
justed V times.
5. Notice how the vertex at the top right corner had its path length adjusted
6. After all vertices have their path lengths we check if a negative cycle is present
PROGRAM CODING:
import java.util.Scanner;
if (N <= 1)
return;
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
a[low + k] = temp[k];
int n, i;
n = scan.nextInt();
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
System.out.print(arr[i]+" ");
System.out.println();
Output:
Result:
Thus the program for the implementation of Bellman ford is created and the output is
verified successfully.
Ex no:11 IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION
AIM :
ALGORITHM:
1. A chain of matrices to be multiplied is given as input.
2. For a sequence A1,A2,A3,A4 of 4 matrices, there are 5 different orderings=5 different
parethesization.
i) (A1,(A2(A3 A4)))
ii) (A1((A2 A3)A4))
iii) ((A1 A2)(A3 A4))
iv) ((A1(A2 A3))A4)
v) (((A1 A2)A3)A4)
Matrix_Multiply(A,B)
If coloumns[A]!=rows[B]
Then error “incomplete dimensions”
Else for i <- 1 to rows[A]
Do for j <- 1 to columns[B]
Do c[I,j] <- 0
For k<- 1 to columns[A]
Do c[i,j]=C[i,j]+A[i,k]+B[i,j]
Return c
4. A parenthesizing of the chain of the matrices is obtained as output.
PROGRAM CODING :
AIM:
ALGORITHM:
4. Select the n_0 least probable messages, and assign them each a digit code.
5. Substitute the selected messages by a composite message summing their probability, and re-order
it.
7. Select D least probable messages, and assign them each a digit code.
8. Substitute the selected messages by a composite message summing their probability, and re-order
it.
9. The code of each message is given by the concatenation of the code digits of the aggregate they've
been put in.
PROGRAM CODING :
import java.util.*;
frequency = freq;
}
super(freq);
value = val;
super(l.frequency + r.frequency);
left = l;
right = r;
if (charFreqs[i] > 0)
HuffmanTree a = trees.poll();
HuffmanTree b = trees.poll();
return trees.poll();
prefix.append('0');
printCodes(node.left, prefix);
prefix.deleteCharAt(prefix.length()-1);
prefix.append('1');
printCodes(node.right, prefix);
prefix.deleteCharAt(prefix.length()-1);
charFreqs[c]++;
System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
}
OUTPUT:
Result:
Thus the program for the implementation of Huffman coding is created and the output
is verified successfully.