The greedy approach of just starting with an empty graph and keep adding valid edges of minimum weight, solves the MST problem.
The only problem is keeping track of the edges that are valid to include.
Kruskal’s Algorithm
Pseudocode
Kruskal's(G,w): Input: undirected graph G=(V,E) with weights w(e). Output: MST edges X1. Sort E by weights, smallest to largest2. Set X to be empty3. For e = (v,w) in E (ordered) 1. If X U e does't have a cycle then X = X U e.4. Output X
This proves the induction case and we have that is always a subset of some MST.
Conclusion
As the algorithm considers adding every edge and adds it if and only if it doesn’t add cycle the output is a spanningtree. This is also minimal as is always a subset of an MST giving the algorithm is correct.
So the only think left to prove Kruskal’s algorithm is correct is the proof of the cut property.
Cut property
Cut property
Let be an undirected graph with an edge weight . Suppose is part of an MST. Let be a cut where no edge of is in the cut edges. Then for of minimum weight - is part of an MST.
Proof
If then and we are done.
Assume .
Let . As is an MST it contains a path from to . As and the path contains an edge .
Let .
We have the size of is
as is a tree.
Consider the cycle - rewrite this cycle as . We will use this to show is connected.
Let . As is connected there must a path in connecting to .
If uses replace by to form which only uses edges in . As connects to we have is connected.
As is connected on and has edges it has to be a spanningtree of .
Note as is the minimum weight edge in we have and moreover
This gives that is of minimum weight as was a MST.
All together this gives us that is an MST where , proving the statement.
Prim's(G,w): Input: undirected graph G=(V,E) with weights w(e). Output: MST defined by the array prevfor all u in V cost(u) = inf prev(u) = nilPick any initial node u_0cost(u_0) = 0H = makequeue(V)while H is not empty: v = deletemin(H) for each {v,z} in E: if cost(z) > w(v,z): cost(z) = w(v,z) prev(z) = v decreasekey(H,z)output prev