0% found this document useful (0 votes)
3 views37 pages

ADA Lab File 2025-3

The document outlines several lab experiments focused on sorting and data merging algorithms, including Merge Sort, Quick Sort, Optimal Merge Patterns, and Huffman Coding. Each experiment includes an introduction to the algorithm, a detailed algorithmic approach, and a sample program with output demonstrating the functionality. The document emphasizes the efficiency and application of these algorithms in computer science.

Uploaded by

fgym497
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

ADA Lab File 2025-3

The document outlines several lab experiments focused on sorting and data merging algorithms, including Merge Sort, Quick Sort, Optimal Merge Patterns, and Huffman Coding. Each experiment includes an introduction to the algorithm, a detailed algorithmic approach, and a sample program with output demonstrating the functionality. The document emphasizes the efficiency and application of these algorithms in computer science.

Uploaded by

fgym497
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

LAB EXPERIMENT- 1

AIM

Write a program for Merge Sort

INTRODUCTION

Divide and Conquer


Divide and conquer is an important algorithm design paradigm based on multi branched
recursion. A divide and conquer algorithm works by recursively breaking down a problem into
two or more sub-problems of the same (or related) type, until these become simple enough to be
solved directly. The solutions to the sub-problems are then combined to give a solution to the
original problem.This technique is the basis of efficient algorithms for all kinds of problems,
such as sorting (e.g., quicksort, merge sort), multiplying large numbers (e.g Karatsuba), syntactic
analysis (e.g., top-down parsers), and computing the discrete Fourier transform (FFTs).

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

MERGE (A1, A2, A)


i.← j 1
A1[m+1], A2[n+1] ← INT_MAX
For k ←1 to m + n do
if A1[i] < A2[j]
then A[k] ← A1[i]
i ← i +1
else
A[k] ← A2[j]
j←j+1
MERGE_SORT (A)
A1[1 . . n/2] ← A[1 . . n/2]
A2[1 . . n/2] ← A[1 + n/2 . . n]
Merge Sort (A1)
Merge Sort (A1)
Merge Sort (A1, A2, A)

PROGRAM
// Merge Sort

#include <iostream>

using namespace std;

// A function to merge the two half into a sorted data.

void Merge(int *a, int low, int high, int mid)

// We have low to mid and mid+1 to high already sorted.

int i, j, k, temp[high-low+1];

i = low;

k = 0;

j = mid + 1;

// Merge the two parts into temp[].

while (i <= mid && j <= high)

if (a[i] < a[j])

temp[k] = a[i];

k++;

i++;
}

else

temp[k] = a[j];

k++;

j++;

// Insert all the remaining values from i to mid into temp[].

while (i <= mid)

temp[k] = a[i];

k++;

i++;

// Insert all the remaining values from j to high into temp[].

while (j <= high)

temp[k] = a[j];

k++;

j++;

}
// Assign sorted data stored in temp[] to a[].

for (i = low; i <= high; i++)

a[i] = temp[i-low];

// A function to split array into two parts.

void MergeSort(int *a, int low, int high)

int mid;

if (low < high)

mid=(low+high)/2;

// Split the data into two half.

MergeSort(a, low, mid);

MergeSort(a, mid+1, high);

// Merge them to get sorted output.

Merge(a, low, high, mid);

int main()

{
int n, i;

cout<<"\nEnter the number of data element to be sorted: ";

cin>>n;

int arr[n];

for(i = 0; i < n; i++)

cout<<"Enter element "<<i+1<<": ";

cin>>arr[i];

MergeSort(arr, 0, n-1);

// Printing the sorted data.

cout<<"\nSorted Data ";

for (i = 0; i < n; i++)

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 the number of data element to be sorted: 10


Enter element 1: 23

Enter element 2: 987

Enter element 3: 45

Enter element 4: 65

Enter element 5: 32

Enter element 6: 9

Enter element 7: 475

Enter element 8: 1

Enter element 9: 17

Enter element 10: 3

Sorted Data ->1->3->9->17->23->32->45->65->475->987


LAB EXPERIMENT- 2

AIM

Write a program for Quick Sort

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

procedure quicksort(array, left, right)

if right > left

select a pivot index //(e.g. pivotIndex := left+(right-left)/2)

pivotNewIndex := partition(array, left, right, pivotIndex)

quicksort(array, left, pivotNewIndex - 1)

quicksort(array, pivotNewIndex + 1, right)

function partition(array, left, right, pivotIndex)

pivotValue := array[pivotIndex]

swap array[pivotIndex] and array[right] // Move pivot to end

storeIndex := left

for i from left to right - 1 // left ≤ i < right

if array[i] ≤ pivotValue

swap array[i] and array[storeIndex]

storeIndex := storeIndex + 1

swap array[storeIndex] and array[right] // Move pivot to its final place

return storeIndex
PROGRAM

#include <iostream>

using namespace std;

// Function to swap two elements

void swap(int &a, int &b) {

int temp = a;

a = b;

b = temp;

// Partition function: Places pivot at correct position and arranges elements

int partition(int arr[], int low, int high) {

int pivot = arr[high]; // Pivot element is the last element

int i = low - 1; // Index of smaller element

for (int j = low; j <= high - 1; j++) {

// If current element is smaller than or equal to pivot

if (arr[j] <= pivot) {

i++; // Increment index of smaller element

swap(arr[i], arr[j]);

swap(arr[i + 1], arr[high]); // Place pivot at the correct position


return (i + 1);

// QuickSort function

void quickSort(int arr[], int low, int high) {

if (low < high) {

// pi is partitioning index

int pi = partition(arr, low, high);

// Separately sort elements before and after partition

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

// Function to print an array

void printArray(int arr[], int size) {

for (int i = 0; i < size; i++)

cout << arr[i] << " ";

cout << endl;

// Main function

int main() {

int arr[] = {10, 7, 8, 9, 1, 5};


int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";

printArray(arr, n);

quickSort(arr, 0, n - 1);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

OUTPUT

Original array: 10 7 8 9 1 5

Sorted array: 1 5 7 8 9 10

Flow of the Program

1. swap() function:

o A simple helper to swap two integers using references.

2. partition() function:

o Picks the last element as the pivot.

o Rearranges the array so that elements smaller than pivot are on the left, bigger on
the right.

o Places pivot in its correct sorted position.


o Returns the pivot's final index.

3. quickSort() function:

o Recursively sorts the two halves: left (low to pi-1) and right (pi+1 to high) based
on pivot.

o Stops when low >= high.

4. printArray() function:

o Just prints the array elements.

5. main() function:

o Defines an array {10, 7, 8, 9, 1, 5}.

o Prints the original array.

o Sorts the array using Quick Sort.

o Prints the sorted array.


LAB EXPERIMENT- 3

AIM

Write a program for Optimal Merge Patterns

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.

 Think of it like building a Huffman Tree.

 Cost here usually means the sum of file sizes after each merge.

Example:

Files of sizes: 20, 30, 10, 5

Merging steps:

1. Merge 5 + 10 → 15 (cost = 15)

2. Merge 15 + 20 → 35 (cost = 35)

3. Merge 30 + 35 → 65 (cost = 65)

Total Cost = 15 + 35 + 65 = 115

ALGORITHM:

At every stage we merge the files of the least length.

Steps:

Create a min heap of the set of elements.

While(heap has more than one element)

{
Delete a minimum element from the heap, and store it in min1;

Delete a minimum element from the heap, and store it in min2;

Create a node with the fields (info, left_link, right_ink);

Let info.node = min1 + min2;

Let left_link.node = min1;

Let right_link_node = min2;

Insert node with valued info into the heap;

struct treenode {

struct treenode *lchild, *rchild;

int weight;

};

typedef struct treenode Type;

Type *Tree(int n)

// list is a global list of n single node

// binary trees as described above.

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

Type *pt = new Type;

// Get a new tree node.

pt -> lchild = Least(list); // Merge two trees with

pt -> rchild = Least(list); // smallest lengths.


pt -> weight = (pt->lchild)->weight

+ (pt->rchild)->weight;

Insert(list, *pt);

return (Least(list)); // Tree left in l is the merge tree.

PROGRAM

#include <iostream>

#include <queue>

#include <vector>

using namespace std;

// Function to find minimum cost to merge files

int optimalMerge(vector<int> files) {

// Create a min-heap (priority queue with smallest on top)

priority_queue<int, vector<int>, greater<int>> minHeap;

// Insert all file sizes into the min-heap

for (int size : files) {

minHeap.push(size);

int totalCost = 0;
// Until only one file remains

while (minHeap.size() > 1) {

// Extract two smallest files

int first = minHeap.top();

minHeap.pop();

int second = minHeap.top();

minHeap.pop();

int mergedSize = first + second;

totalCost += mergedSize;

// Insert merged file back into the heap

minHeap.push(mergedSize);

cout << "Merged files of sizes " << first << " and " << second

<< " for a cost of " << mergedSize << endl;

return totalCost;

// Main function

int main() {
vector<int> files = {20, 30, 10, 5};

cout << "File sizes: ";

for (int size : files) {

cout << size << " ";

cout << endl;

int minCost = optimalMerge(files);

cout << "\nTotal minimum cost of merging = " << minCost << endl;

return 0;

OUTPUT

File sizes: 20 30 10 5

Merged files of sizes 5 and 10 for a cost of 15

Merged files of sizes 15 and 20 for a cost of 35

Merged files of sizes 30 and 35 for a cost of 65

Total minimum cost of merging = 115

Step-by-Step Explanation

1. Insert file sizes {20, 30, 10, 5} into a min-heap.


2. First merge: 5 + 10 = 15

o Cost = 15

o Heap now: {15, 20, 30}

3. Second merge: 15 + 20 = 35

o Cost = 35

o Heap now: {30, 35}

4. Third merge: 30 + 35 = 65

o Cost = 65

o Heap now: {65} (only one file remains)

5. Total cost = 15 + 35 + 65 = 115


LAB EXPERIMENT- 4

AIM

Write a program for Huffman Coding

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

1. Sort source outputs in decreasing order of their probabilities


2. Merge the two least-probable outputs into a single output whose probability is the sum
of the corresponding probabilities.
3. If the number of remaining outputs is more than 2, then go to step 1.
4. Arbitrarily assign 0 and 1 as codewords for the two remaining outputs.
5. If an output is the result of the merger of two outputs in a preceding step, append the
current codeword with a 0 and a 1 to obtain the codeword the the preceding outputs and
repeat step 5. If no output is preceded by another output in a preceding step, then stop.

PROGRAM

#include <iostream>

#include <queue>

#include <unordered_map>

using namespace std;

// Tree node
struct HuffmanNode {

char ch;

int freq;

HuffmanNode *left, *right;

HuffmanNode(char c, int f) {

ch = c;

freq = f;

left = right = nullptr;

};

// Compare function for min-heap

struct Compare {

bool operator()(HuffmanNode* a, HuffmanNode* b) {

return a->freq > b->freq;

};

// Traverse tree and print codes

void printCodes(HuffmanNode* root, string code) {

if (!root)

return;

// Found a leaf node


if (!root->left && !root->right) {

cout << root->ch << ": " << code << "\n";

printCodes(root->left, code + "0");

printCodes(root->right, code + "1");

// Main function to build Huffman Tree

void buildHuffmanTree(string text) {

unordered_map<char, int> freqMap;

// Count frequencies

for (char ch : text) {

freqMap[ch]++;

// Min-heap (priority queue)

priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;

// Create a leaf node for each character

for (auto pair : freqMap) {

pq.push(new HuffmanNode(pair.first, pair.second));

}
// Build the tree

while (pq.size() > 1) {

HuffmanNode *left = pq.top(); pq.pop();

HuffmanNode *right = pq.top(); pq.pop();

HuffmanNode *merged = new HuffmanNode('\0', left->freq + right->freq);

merged->left = left;

merged->right = right;

pq.push(merged);

// Root node

HuffmanNode* root = pq.top();

// Print Huffman codes

cout << "Huffman Codes:\n";

printCodes(root, "");

// Driver code

int main() {

string text = "hello huffman";

buildHuffmanTree(text);

return 0;
}

OUTPUT

Huffman Codes:

a: 000

u: 001

f: 01

e: 1000

h: 1001

m: 101

n: 110

l: 111

How It Works (Steps):

1. Count the frequency of each character.

2. Build a priority queue (min-heap) using frequencies.

3. Combine the two lowest frequency nodes.

4. Repeat until there is one node left (the root of the Huffman Tree).

5. Traverse the tree to assign binary codes.


LAB EXPERIMENT- 5

AIM

Write a program for KNAPSACK Problem

INTRODUCTION

The knapsack problem or rucksack problem is a problem in combinatorial optimization:


Given a set of items, each with a weight and a value, determine the number of each item to
include in a collection so that the total weight is less than a given limit and the total value is as
large as possible. It derives its name from the problem faced by someone who is constrained by a
fixed-size knapsack and must fill it with the most useful items.

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

1. Create a 2D array K[n+1][W+1]

2. For i = 0 to n:

For w = 0 to W:

- If i == 0 or w == 0:

K[i][w] = 0

- Else if w[i-1] <= w:

K[i][w] = max(v[i-1] + K[i-1][w - w[i-1]], K[i-1][w])

- Else:

K[i][w] = K[i-1][w]

3. Return K[n][W] as the max value

PROGRAM

#include <iostream>

#include <vector>

using namespace std;

// Function to solve the 0/1 Knapsack problem

int knapsack(int W, const vector<int>& wt, const vector<int>& val, int n) {

vector<vector<int>> K(n + 1, vector<int>(W + 1, 0));


// Build table K[][] in bottom-up manner

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

for (int w = 0; w <= W; w++) {

if (i == 0 || w == 0) {

K[i][w] = 0; // Base case: no items or no capacity

} else if (wt[i - 1] <= w) {

// Include the item or exclude it

K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);

} else {

// Can't include the item

K[i][w] = K[i - 1][w];

return K[n][W]; // Final result

int main() {

// Example input

vector<int> values = {60, 100, 120};

vector<int> weights = {10, 20, 30};

int capacity = 50;

int n = values.size();
int maxValue = knapsack(capacity, weights, values, n);

cout << "Maximum value in knapsack: " << maxValue << endl;

return 0;

OUTPUT

Maximum value in Knapsack = 220

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:

 values = {60, 100, 120}

 weights = {10, 20, 30}

 capacity = 50

2. Matrix Building:
We build a matrix K[i][w] for each item and weight capacity.

3. Choice at each step:

 If current item weight ≤ current capacity, we choose the maximum of including or


excluding the item.

 Otherwise, we skip the item.

4. Result:
The bottom-right cell K[n][W] contains the maximum value achievable.
LAB EXPERIMENT- 6

AIM

Write a program for Minimum Spanning Trees using Kruskal’s algorithm

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

 Sort all edges in non-decreasing order of their weight.

 Initialize an empty MST.

 Use a Disjoint Set Union (DSU) structure to detect cycles.

 For each edge in sorted order: If it does not form a cycle, add it to the MST.

 Repeat until MST contains V - 1 edges (where V is number of vertices).

PROGRAM

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

// Edge structure

struct Edge {

int u, v, weight;

bool operator<(Edge const& other) {


return weight < other.weight;

};

// Disjoint Set Union (DSU)

class DSU {

vector<int> parent, rank;

public:

DSU(int n) {

parent.resize(n);

rank.resize(n, 0);

for (int i = 0; i < n; i++) parent[i] = i;

int find(int x) {

if (parent[x] != x)

parent[x] = find(parent[x]); // Path compression

return parent[x];

bool union_sets(int a, int b) {

a = find(a);

b = find(b);

if (a == b) return false; // Cycle detected

if (rank[a] < rank[b]) swap(a, b);


parent[b] = a;

if (rank[a] == rank[b]) rank[a]++;

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;

for (Edge e : edges) {

if (dsu.union_sets(e.u, e.v)) {

mst.push_back(e);
mst_cost += e.weight;

cout << "Edges in MST:\n";

for (Edge e : mst) {

cout << e.u << " - " << e.v << " : " << e.weight << "\n";

cout << "Total cost of MST = " << mst_cost << endl;

return 0;

OUTPUT

Edges in the Minimum Spanning Tree:

0 -- 1 = 1

1 -- 2 = 2

0 -- 3 = 4

Total weight of MST: 7


LAB EXPERIMENT- 7

AIM

Write a program for Minimum Spanning Trees using Prim’s algorithm

INTRODUCTION

A Minimum Spanning Tree (MST) is a subset of edges that connects all vertices in a
connected, undirected, weighted graph, such that:

 There are no cycles.

 The total edge weight is minimized.

Prim’s Algorithm is a greedy algorithm that builds the MST by:

 Starting from an arbitrary vertex.

 Repeatedly adding the smallest edge that connects a vertex inside the MST to one
outside.

ALGORITHM

1. Start with any node and mark it as part of the MST.


2. Find the edge with the minimum weight that connects a node in the MST to a node
outside.
3. Add this edge to the MST.
4. Repeat step 2 until all vertices are included.

PROGRAM

#include <iostream>

#include <climits>

using namespace std;

#define V 5 // Number of vertices in the graph


// Function to find the vertex with the minimum key value not yet included in MST

int minKey(int key[], bool mstSet[]) {

int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)

if (!mstSet[v] && key[v] < min)

min = key[v], min_index = v;

return min_index;

// Function to print the constructed MST

void printMST(int parent[], int graph[V][V]) {

int totalWeight = 0;

cout << "Edge \tWeight\n";

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

cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << endl;

totalWeight += graph[i][parent[i]];

cout << "Total weight of MST: " << totalWeight << endl;

// Function that implements Prim's algorithm

void primMST(int graph[V][V]) {


int parent[V]; // Stores constructed MST

int key[V]; // Key values used to pick minimum weight edge

bool mstSet[V]; // To represent set of vertices included in MST

// Step 1: Initialize all keys as INFINITE and mstSet[] as false

for (int i = 0; i < V; i++)

key[i] = INT_MAX, mstSet[i] = false;

// Step 2: Start from the first vertex

key[0] = 0; // Make key 0 so that this vertex is picked first

parent[0] = -1; // First node is always root of MST

// The MST will have V vertices, so repeat V-1 times

for (int count = 0; count < V - 1; count++) {

// Step 3: Pick the minimum key vertex not yet included in MST

int u = minKey(key, mstSet);

mstSet[u] = true;

// Step 4: Update key and parent of adjacent vertices

for (int v = 0; v < V; v++)

if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v])

parent[v] = u, key[v] = graph[u][v];

// Step 5: Print the result


printMST(parent, graph);

// Main function

int main() {

// Representation of graph using adjacency matrix

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}

};

primMST(graph); // Call Prim's algorithm

return 0;

OUTPUT

Edge Weight

0-1 2

1-2 3

0-3 6

1-4 5

Total weight of MST: 16


LAB EXPERIMENT- 8

AIM

Write a program for floyd-Warshall algorithm

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

Let dist[i][j] be the shortest distance from vertex i to vertex j.

1. Initialize dist[i][j] = weight(i, j) if edge exists, else INF.

2. Set dist[i][i] = 0 for all i.

3. For each vertex k, update every pair (i, j) as:

if dist[i][k] + dist[k][j] < dist[i][j]:

dist[i][j] = dist[i][k] + dist[k][j]

PROGRAM

#include <iostream>

using namespace std;

#define V 4

#define INF 99999 // A large value representing infinity

void floydWarshall(int graph[V][V]) {


int dist[V][V];

// Step 1: Initialize distance matrix

for (int i = 0; i < V; i++)

for (int j = 0; j < V; j++)

dist[i][j] = graph[i][j];

// Step 2: Update distances using intermediate vertices

for (int k = 0; k < V; k++) {

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

if (dist[i][k] + dist[k][j] < dist[i][j])

dist[i][j] = dist[i][k] + dist[k][j];

// Step 3: Print shortest distance matrix

cout << "Shortest distances between every pair of vertices:\n";

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

if (dist[i][j] == INF)

cout << "INF\t";

else

cout << dist[i][j] << "\t";


}

cout << endl;

int main() {

int graph[V][V] = {

{0, 5, INF, 10},

{INF, 0, 3, INF},

{INF, INF, 0, 1},

{INF, INF, INF, 0}

};

floydWarshall(graph);

return 0;

OUTPUT

Shortest distances between every pair of vertices:

0 5 8 9

INF 0 3 4

INF INF 0 1

INF INF INF 0

You might also like