簡單更詳細的實現

為了有效地處理迴圈檢測,我們將每個節點視為樹的一部分。新增邊時,我們檢查它的兩個元件節點是否是不同樹的一部分。最初,每個節點組成一個單節點樹。

algorithm kruskalMST'(G: a graph)
    sort G's edges by their value
    MST = a forest of trees, initially each tree is a node in the graph
    for each edge e in G:
        if the root of the tree that e.first belongs to is not the same 
        as the root of the tree that e.second belongs to:
            connect one of the roots to the other, thus merging two trees
    
    return MST, which now a single-tree forest