Union-Find Algorithm
Union-Find Algorithm for Disjoint Set
Initialization of parents and ranks:
1 2 3 4 5 6 7 8 9 |
|
Find algorithm:
1 2 3 4 5 6 7 8 |
|
Find Algorithm with Path compression:
Why Path compression? Because ultimately we want to reach the root parent of the tree. What if we set the root parent directly for the given element? This way we don't have to traverse the tree to find the root parent.
1 2 3 4 5 6 7 8 9 |
|
Union Algorithm:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Union by Rank Algorithm:
Why do we need the ranking? Because with simple Union operation, a chain is formed that takes O(n) time to find the parent in the worst case and then unionize two elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Kruskal's Algorithm
With Kruskal's algorithm we find the Minimum Spanning Tree of any Graph. A MST is a graph which has the minimum number of least costly edges which can create a connected graph. In a Kruskal's algorithm we are given an array of edges along with their weights and asked to return an array of edges that are required to create a MST.
For the given graph below:
graph TD
A --10--> B
A --15--> C
B --5--> C
B --10--> D
C --20--> D
C --25--> E
D --15--> E
The MST is as follows:
graph TD
A --10--> B
B --5--> C
B --10--> D
D --15--> E
Kruskal's Algorithm:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|