JNTUA Advanced Data Structures and Algorithms Lab Manual R20
JNTUA Advanced Data Structures and Algorithms Lab Manual R20
me/jntua
Ex.No:1 Date:
Aim:
Write a program to implement the following operations on Binary Search
Tree
a) Insert b) Delete c) Search d) Display
Description:
Binary Search Tree is a binary tree in which every node contains only
smaller values in its left subtree and only larger values in its right
subtree. There must be no duplicate nodes.
It is called a binary tree because each tree node has a maximum of
two children.
It is called a search tree because it can be used to search for the
presence of a number in O(log(n)) time.
The following operations are performed on a binary search tree...
1. Insertion
2. Search
3. Deletion
Procedure:
1. Insertion Operation in BST
In a binary search tree, the insertion operation is performed with O(log n)
time complexity. In binary search tree, new node is always inserted as a leaf
node.
The insertion operation is performed as follows...
Step 1 - Create a newNode with given value and set its left and right to
NULL.
Step 2 - Check whether tree is Empty.
Step 3 - If the tree is Empty, then set root to newNode.
Step 4 - If the tree is Not Empty, then check whether the value of
newNode is smaller or larger than the node (here it is root node).
Step 5 - If newNode is smaller than or equal to the node then move to its
left child. If newNode is larger than the node then move to its right
child.
Step 6- Repeat the above steps until we reach to the leaf node (i.e.,
reaches to NULL).
Step 7-After reaching the leaf node, insert the newNode as left child if the
newNode is smaller or equal to that leaf node or else insert it as
right child.
Search Operation in BST
In a binary search tree, the search operation is performed with O(log n)
time complexity. The search operation is performed as follows...
Deleting a node from Binary search tree includes following three cases...
int data;
Node left;
Node right;
//Assign data to the new node, set left and right children to null
this.data = data;
this.left = null;
this.right = null;
public BinarySearchTree(){
root = null;
if(root == null){
root = newNode;
return;
else {
while(true) {
parent = current;
//If data is less than current's data, node will be inserted to the left of tree
current = current.left;
if(current == null) {
parent.left = newNode;
return;
//If data is greater than current's data, node will be inserted to the right of tree
else {
current = current.right;
if(current == null) {
parent.right = newNode;
return;
if (root.left != null)
return minNode(root.left);
else
return root;
//deleteNode() will delete the given node from the binary search tree
if(node == null){
return null;
else {
//value is less than node's data then, search the value in left subtree
//value is greater than node's data then, search the value in right subtree
//If value is equal to node's data that is, we have found the node to be deleted
else {
//If node to be deleted has no child then, set the node to null
node = null;
node = node.right;
node = node.left;
else {
node.data = temp.data;
return node;
if(root == null){
System.out.println("Tree is empty");
return;
else {
if(node.left!= null)
inorderTraversal(node.left);
if(node.right!= null)
inorderTraversal(node.right);
bt.insert(50);
bt.insert(30);
bt.insert(70);
bt.insert(60);
bt.insert(10);
bt.insert(90);
bt.inorderTraversal(bt.root);
bt.inorderTraversal(bt.root);
bt.inorderTraversal(bt.root);
bt.inorderTraversal(bt.root);
Ex.No: 2 Date:
Aim:
Write a program to perform a Binary Search for a given set of integer
values
Description:
In the binary search algorithm, we can find the element position using the
following methods.
a) Recursive Method
b) Iterative Method
The divide and conquer approach technique is followed by the recursive method.
In this method, a function is called itself again and again until it found an
element in the list.
Procedure:
USING RECURSIVE:
class BST
int data;
Node left;
Node right;
this.data=data;
if(root==null)
root=new Node(val);
return root;
if(root.data>val)
root.left=insert(root.left,val);
else
root.right=insert(root.right,val);
return root;
if(root==null)
return;
inorder(root.left);
System.out.println(root.data+" ");
inorder(root.right);
int val[]={3,4,6,7,9,5,8};
Node root=null;
for(int i=0;i<val.length;i++)
root=insert(root,val[i]);
inorder(root);
2. Iterative Method
class BST
{
private static class Node
int data;
Node left;
Node right;
this.data=data;
if(root==null)
root=new Node(val);
return root;
if(root.data>val)
root.left=insert(root.left,val);
else
root.right=insert(root.right,val);
return root;
if(root==null)
return;
inorder(root.left);
System.out.println(root.data+" ");
inorder(root.right);
int val[]={3,4,6,7,9,5,8};
Node root=null;
for(int i=0;i<val.length;i++)
root=insert(root,val[i]);
inorder(root);
Ex.No: 3 Date:
Aim:
Write a program to implement Splay trees.
Description:
Splay tree is self-balancing BST.
The main idea of splay tree is to bring the recently accessed item to root
of the tree, this makes the recently searched item to be accessible in O(1)
time if accessed again.
The worst case time complexity of Binary Search Tree (BST) operations
like search, delete, insert is O(n). The worst case occurs when the tree is
skewed. We can get the worst case time complexity as O(Logn)
with AVL and Red-Black Trees.
All splay tree operations run in O(log n) time on average, where n is the
number of entries in the tree. Any single operation can take Theta(n)
time in the worst case.
class SPLAY
int key;
};
Node.key = key;
return (Node);
node y = x.left;
x.left = y.right;
y.right = x;
return y;
node y = x.right;
x.right = y.left;
y.left = x;
return y;
return root;
if (root.left == null)
return root;
root = rightRotate(root);
if (root.left.right != null)
root.left = leftRotate(root.left);
else
if (root.right == null)
return root;
root.right.left = splay(root.right.left,key);
if (root.right.left != null)
root.right = rightRotate(root.right);
root = leftRotate(root);
if (root != null)
preOrder(root.left);
preOrder(root.right);
{
Computer Science and Engineering Page 19
root.left = newNode(50);
root.right = newNode(200);
root.left.left = newNode(40);
root.left.left.left = newNode(30);
root.left.left.left.left = newNode(20);
preOrder(root);
Ex.No: 4 Date:
Aim:
Write a program to implement Merge sort for the given list of integer
values.
Description:
Merge Sort
Merge Sort is a Divide and Conquer algorithm. It divides input
array in two halves, calls itself for the two halves and then merges
the two sorted halves.
The merge() function is used for merging two halves.
The merge(arr, l, m, r) is key process that assumes that arr[l..m]
and arr[m+1..r] are sorted and merges the two sorted sub-arrays
into one.
Three main components of the divide-and-conquer approach to algorithm design:
parts.
3. Combine: merge all solutions for all smaller parts into a single
class MergeSort
int n1 = m - l + 1;
int n2 = r - m;
int i = 0, j = 0;
int k = l;
arr[k] = L[i];
i++;
else
arr[k] = R[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
if (l < r)
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
int n = arr.length;
Computer Science and Engineering Page 23
System.out.println();
System.out.println("Given Array");
printArray(arr);
System.out.println("\nSorted array");
printArray(arr);
Ex.No: 5 Date:
Aim:
Write a program to implement Quick sort for the given list of integer values.
Description:
QuickSort is a Divide and Conquer algorithm. It picks an element
as pivot and partitions the given array around the picked pivot.
There are many different versions of quickSort that pick pivot in
different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
import java.util.*;
class Main
{
//partitions the array around pivot=> last element
static int partition(int numArray[], int low, int high)
{
int pivot = numArray[high];
// smaller element index
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
// check if current element is less than or equal to pivot
if (numArray[j] <= pivot) {
i++;
// swap the elements
int temp = numArray[i];
numArray[i] = numArray[j];
numArray[j] = temp;
}
}
// swap numArray[i+1] and numArray[high] (or pivot)
int temp = numArray[i + 1];
numArray[i + 1] = numArray[high];
numArray[high] = temp;
return i + 1;
}
Output:
Original Array:[3, 2, 6, -1, 9, 1, -6, 10, 5]
Sorted Array:[-6, -1, 1, 2, 3, 6, 9, 10, 5]
Ex.No: 6 Date:
Aim:
Write a program to find the solution for the knapsack problem using the
greedy method.
Description:
Input:
Items as (value, weight) pairs
arr[] = {{60, 10}, {100, 20}, {120, 30}}
Knapsack Capacity, W = 50;
Output:
Maximum possible value = 240
by taking items of weight 10 and 20 kg and 2/3 fraction
of 30 kg. Hence total price will be 60+100+(2/3)(120) = 240
import java.util.Scanner;
class Knapsack
int object,m;
object=sc.nextInt();
for(int i=0;i<object;i++)
profit[i]=sc.nextInt();
weight[i]=sc.nextInt();
m=sc.nextInt();
for(int i=0;i<object;i++)
p_w[i]=(double)profit[i]/(double)weight[i];
System.out.println("");
System.out.println("-------------------");
System.out.println("-----Data-Set------");
System.out.print("-------------------");
System.out.println("");
System.out.print("Objects");
for(int i=1;i<=object;i++)
System.out.print(i+" ");
System.out.println();
System.out.print("Profit ");
for(int i=0;i<object;i++)
System.out.print(profit[i]+" ");
System.out.println();
System.out.print("Weight ");
for(int i=0;i<object;i++)
System.out.print(weight[i]+" ");
System.out.println();
System.out.print("P/W ");
for(int i=0;i<object;i++)
System.out.print(p_w[i]+" ");
for(int i=0;i<object-1;i++)
{
Computer Science and Engineering Page 30
for(int j=i+1;j<object;j++)
if(p_w[i]<p_w[j])
double temp=p_w[j];
p_w[j]=p_w[i];
p_w[i]=temp;
int temp1=profit[j];
profit[j]=profit[i];
profit[i]=temp1;
int temp2=weight[j];
weight[j]=weight[i];
weight[i]=temp2;
System.out.println("");
System.out.println("-------------------");
System.out.println("--After Arranging--");
System.out.print("-------------------");
System.out.println("");
System.out.print("Objects");
for(int i=1;i<=object;i++)
System.out.print(i+" ");
System.out.println();
System.out.print("Profit ");
Computer Science and Engineering Page 31
for(int i=0;i<object;i++)
System.out.print(profit[i]+" ");
System.out.println();
System.out.print("Weight ");
for(int i=0;i<object;i++)
System.out.print(weight[i]+" ");
System.out.println();
System.out.print("P/W ");
for(int i=0;i<object;i++)
System.out.print(p_w[i]+" ");
int k=0;
double sum=0;
System.out.println();
while(m>0)
if(weight[k]<m)
sum+=1*profit[k];
m=m-weight[k];
else
{
Computer Science and Engineering Page 32
double x4=m*profit[k];
double x5=weight[k];
double x6=x4/x5;
sum=sum+x6;
m=0;
k++;
Ex.No:7 Date:
Aim:
Write a program to find minimum cost spanning tree using Prim’s
algorithm.
Description:
How does Prim’s Algorithm Work? The idea behind Prim’s algorithm is
simple, a spanning tree means all vertices must be connected. So the
two disjoint subsets (discussed above) of vertices must be connected to
make a Spanning Tree. And they must be connected with the minimum
weight edge to make it a Minimum Spanning Tree.
Algorithm :
import java.io.*;
import java.lang.*;
import java.util.*;
class MST {
// in MST
min = key[v];
min_index = v;
return min_index;
Computer Science and Engineering Page 35
// stored in parent[]
System.out.println("Edge \tWeight");
+ graph[i][parent[i]]);
// cut
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
mstSet[u] = true;
// than key[v]
parent[v] = u;
key[v] = graph[u][v];
printMST(parent, graph);
23
(0)--(1)--(2)
|/\|
6| 8/ \5 |7
|/ \|
(3)-------(4)
9 */
t.primMST(graph);
Ex.No:8 Date:
Aim:
Kruskal's algorithm to find the minimum cost spanning tree uses the greedy
approach. This algorithm treats the graph as a forest and every node it has as
an individual tree. A tree connects to another only and only if, it has the least
cost among all available options and does not violate MST properties.
Algorithm :
import java.io.*;
import java.lang.*;
import java.util.*;
};
// union-find
class subset {
};
Graph(int v, int e)
V = v;
E = e;
// (path compression)
if (subsets[i].parent != i)
subsets[i].parent
= find(subsets, subsets[i].parent);
return subsets[i].parent;
subsets[xroot].parent = yroot;
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
// algorithm
void KruskalMST()
int e = 0;
int i = 0;
// array of edges
Arrays.sort(edge);
subsets[v].parent = v;
subsets[v].rank = 0;
while (e < V - 1) {
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
int minimumCost = 0;
+ result[i].dest
minimumCost += result[i].weight;
+ minimumCost);
// Driver's Code
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
graph.edge[2].src = 0;
graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
// Function call
graph.KruskalMST();
Ex.No:9 Date:
Aim:
Write a program to find a single source shortest path for a given graph.
Description:
Bellman-Ford single source shortest path algorithm is a below :
Computer Science and Engineering Page 50
Algorithm :
1. Initialize the distance from the source node S to all other nodes as
infinite (999999999) and to itself as 0.
Distance [ AllNodes ] = 999999999, Distance [ S ] = 0.
2. For every node in the graph
3. For every edge E in the EdgeList
4. Node_u = E.first, Node_v = E.second
5. Weight_u_v = EdgeWeight ( Node_u, Node_v )
6. If ( Distance [ v ] > Distance [ u ] + Weight_u_v )
7. Distance [ v ] = Distance [ u ] + Weight_u_v
import java.io.*;
import java.lang.*;
import java.util.*;
class ShortestPath {
min = dist[v];
min_index = v;
return min_index;
// array
Computer Science and Engineering Page 52
System.out.println(
// to i is finalized
// as false
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}
Computer Science and Engineering Page 53
dist[src] = 0;
sptSet[u] = true;
printSolution(dist);
// Driver's code
*/
int graph[][]
= new int[][] { { 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 } };
// Function call
t.dijkstra(graph, 0);
Ex.No:10 Date:
Aim:
Write a program to find the solution for job sequencing with deadlines
problems.
Description:
Job sequencing is the set of jobs, associated with the job i where
deadline di >= 0 and profit pi > 0. For any job i the profit is earned if and only
if the job is completed by its deadline. To complete a job, one has to process
the job on a machine for one unit of time. Only one machine is available for
processing the jobs.
Input: A is the array of jobs with deadline and profit S array will be the
output.
1. Begin
2. Sort all the jobs based on profit Pi so
3. P1 > P2 > P3 ............................... >=Pn
4. d = maximum deadline of job in A
5. Create array S[1,… ............. ,d]
6. For i=1 to n do
7. Find the largest job x
8. For j=i to 1
9. If ((S[j] = 0) and (x deadline<= d))
10. Then
11. S[x] = i;
12. Break;
13. End if
14. End for
15. End for
16. End
Procedure:
Steps for performing job sequencing with deadline using greedy approach is as
follows:
import java.util.*;
class Job
char id;
// Constructors
public Job() {}
this.id = id;
this.deadline = deadline;
this.profit = profit;
// Length of array
int n = arr.size();
// profit
Collections.sort(arr,
for (int j
j >= 0; j--) {
if (result[j] == false) {
result[j] = true;
job[j] = arr.get(i).id;
break;
System.out.println();
// Driver's code
{
Computer Science and Engineering Page 59
// Function call
job.printJobScheduling(arr, 3);
Ex.No:11 Date:
Aim:
Write a program to find the solution for a 0-1 knapsack problem using
dynamic programming.
Description:
● The value or profit obtained by putting the items into the knapsack is
maximum.
● And the weight limit of the knapsack does not exceed.
maximum value subset of val[] such that sum of the weights of this
Procedure:
the total weight and value of all subsets. Consider the only subsets whose
total weight is smaller than W. From all such subsets, pick the maximum
value subset.
Therefore, the maximum value that can be obtained from ‘n’ items is
2. Value of nth item plus maximum value obtained by n-1 items and W
If the weight of ‘nth’ item is greater than ‘W’, then the nth item cannot
class Knapsack {
Ex.No:12 Date:
Aim:
Write a program to solve the Sum of subsets problem for a given set of
distinct numbers using backtracking.
Description:
Subset sum problem is the problem of finding a subset such that the sum of
elements equals a given number. The backtracking approach generates all
permutations in the worst case but in general, performs better than the
recursive approach towards subset sum problem.
Algorithm:
subsetSum(set, subset, n, subSize, total, node, sum)
Input − The given set and subset, size of set and subset, a total of the
subset, number of elements in the subset and the given sum.
Output − All possible subsets whose sum is the same as the given sum.
Begin
if total = sum, then display the subset
//go for finding next subset
subsetSum(set, subset, , subSize-1, total-
set[node], node+1, sum) return
else
for all element i in the set, do subset[subSize] := set[i]
subSetSum(set, subset, n, subSize+1,
total+set[i], i+1, sum) done
End
import java.io.*;
class GFG {
// Base Cases
if (sum == 0)
return true;
if (n == 0)
return false;
/* Driver code */
int sum = 9;
int n = set.length;
System.out.println("Found a subset"
else
Ex.No:13 Date:
Aim:
Description:
N Queens problem :
Consider below chessboards of size 4, the board on the left side is valid in
which no two queens can attack each other; whereas the board on the right
is invalid.
Algorithm : N Queens
diagonal, then
return false;
return true;
return true;
}
}
boolean solveNQ()
{
int board[][] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
System.out.print("Solution does not exist");
return false;
}
printSolution(board);
return true;
}