Algorithms
Algorithms
& Algorithms
Session-18
Algorithms 1
Minimum-Cost Spanning Tree
Algorithms 2
Example
8 10 14
1 3 5 7
7 4 12 6 3
2
2 4 6 8
9
Algorithms 5
Kruskal’s Method
8 10 14
1 3 5 7 1 3 5 7
7 4 12 6 3
2
2 4 6 8 2 4 6 8
9
Algorithms 11
Pseudocode For Kruskal’s Method
Edge set E.
Operations are:
Is E empty?
Select and remove a least-cost edge.
Use a min heap of edges.
Initialize. O(e) time.
Remove and return least-cost edge. O(log e) time.
Algorithms 13
Data Structures For Kruskal’s Method
Algorithms 14
Data Structures For Kruskal’s Method
Use an array linear list for the edges of T.
Does T have n - 1 edges?
• Check size of linear list. O(1) time.
Does the addition of an edge (u, v) to T result in a
cycle?
• Not easy.
Add an edge to T.
• Add at right end of linear list. O(1) time.
Just use an array rather than ArrayLinearList.
Algorithms 15
Data Structures For Kruskal’s Method
Does the addition of an edge (u, v) to T result in
a cycle?
1 3 5 7
7 4 6 3
2
2 4 6 8
2 4 6 8
Algorithms 20
Shortest Path Problems
14
A path from 1 to 7.
Path length is 14.
Example
8 6
1
2 3
3 1
16
6 7 4 5 10
4
2 4 7
5 3
14
14
1 3 6 7 11
Greedy Single Source All Destinations
1 3 6 7 11
Single Source Single Destination