Skip to main content

Kruskal's Algorithm

Definition​

Kruskal's Algorithm is a greedy algorithm used to find the minimum spanning tree (MST) of a connected, undirected graph. It works by selecting edges in increasing order of weight until all vertices are connected without forming a cycle

Practice​

kruskalMST(graph):
edges = graph.getAllEdges() // Retrieve all edges from the graph
edges.sort() // Sort edges in non-decreasing order of weight
MST = new Graph() // Initialize an empty graph to hold the MST
disjointSet = new DisjointSet() // Initialize a disjoint-set data structure

for edge in edges:
if !disjointSet.isSameSet(edge.start, edge.end):
// Adding this edge does not form a cycle
MST.addEdge(edge.start, edge.end, edge.weight) // Add edge to the MST
disjointSet.union(edge.start, edge.end) // Union the sets of the vertices

if MST.numEdges == MST.numVertices - 1:
break // MST is complete when all vertices are connected

return MST