ADA Lab File 2025-3
ADA Lab File 2025-3
AIM
INTRODUCTION
Merge sort
Merge sort is an O(n log n) comparison-based sorting algorithm. In most implementations it is
stable, meaning that it preserves the input order of equal elements in the sorted output. It is an
example of the divide and conquer algorithmic paradigm
ALGORITHM
Steps:
1. If the list is of length 0 or 1, then it is already sorted. Otherwise
2. Divide the unsorted list into two sublists of about half the size
3. Sort each sublist recursively by re-applying merge sort.
4. Merge the two sublists back into one sorted list
PROGRAM
// Merge Sort
#include <iostream>
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;
temp[k] = a[i];
k++;
i++;
}
else
temp[k] = a[j];
k++;
j++;
temp[k] = a[i];
k++;
i++;
temp[k] = a[j];
k++;
j++;
}
// Assign sorted data stored in temp[] to a[].
a[i] = temp[i-low];
int mid;
mid=(low+high)/2;
int main()
{
int n, i;
cin>>n;
int arr[n];
cin>>arr[i];
MergeSort(arr, 0, n-1);
cout<<"->"<<arr[i];
return 0;
OUTPUT
In this case, we are entering the elements to be sorted using Merge Sort: “23, 987, 45, 65, 32, 9,
475, 1, 17, and 3.”
Enter element 3: 45
Enter element 4: 65
Enter element 5: 32
Enter element 6: 9
Enter element 8: 1
Enter element 9: 17
AIM
INTRODUCTION
Quick sort is a recursive sorting algorithm following the 'divide et impera' scheme. it takes an
element (token) of the list that is to sort and transfers every element that smaller on the one side
and everything that is bigger on the other. for the whole list, the algorithm is used on the two
parts again until the list is sorted.
ALGORITHM
pivotValue := array[pivotIndex]
storeIndex := left
if array[i] ≤ pivotValue
storeIndex := storeIndex + 1
return storeIndex
PROGRAM
#include <iostream>
int temp = a;
a = b;
b = temp;
swap(arr[i], arr[j]);
// QuickSort function
// pi is partitioning index
quickSort(arr, pi + 1, high);
// Main function
int main() {
printArray(arr, n);
quickSort(arr, 0, n - 1);
printArray(arr, n);
return 0;
OUTPUT
Original array: 10 7 8 9 1 5
Sorted array: 1 5 7 8 9 10
1. swap() function:
2. partition() function:
o Rearranges the array so that elements smaller than pivot are on the left, bigger on
the right.
3. quickSort() function:
o Recursively sorts the two halves: left (low to pi-1) and right (pi+1 to high) based
on pivot.
4. printArray() function:
5. main() function:
AIM
INTRODUCTION
When you have multiple sorted files and you want to merge them into one with
minimum total computation cost, you should always merge the two smallest files first.
Cost here usually means the sum of file sizes after each merge.
Example:
Merging steps:
ALGORITHM:
Steps:
{
Delete a minimum element from the heap, and store it in min1;
struct treenode {
int weight;
};
Type *Tree(int n)
+ (pt->rchild)->weight;
Insert(list, *pt);
PROGRAM
#include <iostream>
#include <queue>
#include <vector>
minHeap.push(size);
int totalCost = 0;
// Until only one file remains
minHeap.pop();
minHeap.pop();
totalCost += mergedSize;
minHeap.push(mergedSize);
cout << "Merged files of sizes " << first << " and " << second
return totalCost;
// Main function
int main() {
vector<int> files = {20, 30, 10, 5};
cout << "\nTotal minimum cost of merging = " << minCost << endl;
return 0;
OUTPUT
File sizes: 20 30 10 5
Step-by-Step Explanation
o Cost = 15
3. Second merge: 15 + 20 = 35
o Cost = 35
4. Third merge: 30 + 35 = 65
o Cost = 65
AIM
INTRODUCTION:
Given a set of messages with probabilities p1 p2 pn, the Huffman code tree is constructed by
recursively combining subtrees:
1. Begin with n trees, each consists of a single node corresponding to one message word, with
the weight of pi
2. Repeat until there is only one tree
_ pick two subtrees with smallest weights
_ combine them by adding a new node as root, and make the two trees its children.The weight of
the new tree is the sum of the weight of two subtrees
With a heap, each step of combining tree takes O(log n) time, and the total time is O(n log n).
ALGORITHM
PROGRAM
#include <iostream>
#include <queue>
#include <unordered_map>
// Tree node
struct HuffmanNode {
char ch;
int freq;
HuffmanNode(char c, int f) {
ch = c;
freq = f;
};
struct Compare {
};
if (!root)
return;
cout << root->ch << ": " << code << "\n";
// Count frequencies
freqMap[ch]++;
}
// Build the tree
merged->left = left;
merged->right = right;
pq.push(merged);
// Root node
printCodes(root, "");
// Driver code
int main() {
buildHuffmanTree(text);
return 0;
}
OUTPUT
Huffman Codes:
a: 000
u: 001
f: 01
e: 1000
h: 1001
m: 101
n: 110
l: 111
4. Repeat until there is one node left (the root of the Huffman Tree).
AIM
INTRODUCTION
The problem often arises in resource allocation with financial constraints. A similar problem also
appears in combinatory, complexity theory, cryptography and applied mathematics.
In the following, we have n kinds of items, 1 through n. Each kind of item i has a value vi and a
weight wi. We usually assume that all values and weights are nonnegative. The maximum weight
that we can carry in the bag is W.
The most common formulation of the problem is the 0-1 knapsack problem, which restricts the
number xi of copies of each kind of item to zero or one. Mathematically the 0-1-knapsack
problem can be formulated as:
maximize
subject to
The bounded knapsack problem restricts the number xi of copies of each kind of item to a
maximum integer value ci. Mathematically the bounded knapsack problem can be formulated as:
maximize
subject to
The unbounded knapsack problem places no upper bound on the number of copies of each
kind of item.
Of particular interest is the special case of the problem with these properties:
it is a decision problem,
it is a 0-1 problem,
for each kind of item, the weight equals the value: wi = vi.
Notice that in this special case, the problem is equivalent to this: given a set of nonnegative
integers, does any subset of it add up to exactly W? Or, if negative weights are allowed and W is
chosen to be zero, the problem is: given a set of integers, does any subset add up to exactly 0?
This special case is called the subset sum problem. In the field of cryptography the term
knapsack problem is often used to refer specifically to the subset sum problem.
If multiple knapsacks are allowed, the problem is better thought of as the bin packing problem.
ALGORITHM
2. For i = 0 to n:
For w = 0 to W:
- If i == 0 or w == 0:
K[i][w] = 0
- Else:
K[i][w] = K[i-1][w]
PROGRAM
#include <iostream>
#include <vector>
if (i == 0 || w == 0) {
} else {
int main() {
// Example input
int n = values.size();
int maxValue = knapsack(capacity, weights, values, n);
cout << "Maximum value in knapsack: " << maxValue << endl;
return 0;
OUTPUT
Step-by-Step Explanation
We use a 2D array K [n+1][W+1] where K[i][w] represents the maximum value that can be
obtained using the first i items and capacity w.
1. Input:
capacity = 50
2. Matrix Building:
We build a matrix K[i][w] for each item and weight capacity.
4. Result:
The bottom-right cell K[n][W] contains the maximum value achievable.
LAB EXPERIMENT- 6
AIM
INTRODUCTION
Kruskal's Algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of
a connected, undirected, weighted graph.
An MST is a subset of the edges that connects all the vertices together, without any cycles and
with the minimum possible total edge weight.
ALGORITHM
For each edge in sorted order: If it does not form a cycle, add it to the MST.
PROGRAM
#include <iostream>
#include <vector>
#include <algorithm>
// Edge structure
struct Edge {
int u, v, weight;
};
class DSU {
public:
DSU(int n) {
parent.resize(n);
rank.resize(n, 0);
int find(int x) {
if (parent[x] != x)
return parent[x];
a = find(a);
b = find(b);
return true;
};
int main() {
int V = 4;
vector<Edge> edges = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4}
};
// Kruskal’s algorithm
sort(edges.begin(), edges.end());
DSU dsu(V);
int mst_cost = 0;
vector<Edge> mst;
if (dsu.union_sets(e.u, e.v)) {
mst.push_back(e);
mst_cost += e.weight;
cout << e.u << " - " << e.v << " : " << e.weight << "\n";
cout << "Total cost of MST = " << mst_cost << endl;
return 0;
OUTPUT
0 -- 1 = 1
1 -- 2 = 2
0 -- 3 = 4
AIM
INTRODUCTION
A Minimum Spanning Tree (MST) is a subset of edges that connects all vertices in a
connected, undirected, weighted graph, such that:
Repeatedly adding the smallest edge that connects a vertex inside the MST to one
outside.
ALGORITHM
PROGRAM
#include <iostream>
#include <climits>
return min_index;
int totalWeight = 0;
cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << endl;
totalWeight += graph[i][parent[i]];
cout << "Total weight of MST: " << totalWeight << endl;
// Step 3: Pick the minimum key vertex not yet included in MST
mstSet[u] = true;
// Main function
int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
return 0;
OUTPUT
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
AIM
INTRODUCTION
The Floyd-Warshall Algorithm is used to find the shortest paths between all pairs of vertices
in a weighted graph. It works for both directed and undirected graphs and can handle positive
and negative weights (but no negative weight cycles).
ALGORITHM
PROGRAM
#include <iostream>
#define V 4
dist[i][j] = graph[i][j];
if (dist[i][j] == INF)
else
int main() {
int graph[V][V] = {
{INF, 0, 3, INF},
};
floydWarshall(graph);
return 0;
OUTPUT
0 5 8 9
INF 0 3 4
INF INF 0 1