Algorithm Prim's Algorithm
Algorithm Prim's Algorithm
1. Initialize:
visited[] = [false, false, ..., false] // All vertices are unvisited
visited[0] = true // Start from vertex 0
mincost = 0 // Total cost of MST
edgecount = 0 // Count of edges in MST
1. Initialize:
dist[] = {∞, ∞, ..., ∞} // Distance to all vertices is initially infinity
dist[src] = 0 // Distance to the source is 0
sptSet[] = {false, false, ..., false} // No vertex is included in SPT
Output: Shortest distance from the source vertex to all other vertices.
Kruskal
1. Initialize the graph with vertices and edges.
2. Sort the edges in non-decreasing order of their weights.
3. Initialize the `parent` array for Union-Find.
4. Create an empty list to store the edges of the MST.
5. For each edge (source, destination, weight) in sorted edges:
a. Find the root of the source vertex.
b. Find the root of the destination vertex.
c. If the roots are different:
i. Add the edge to the MST.
ii. Union the two sets by updating the parent array.
6. Output the edges of the MST.