Here is Kruskal's algorithm:
function kruskal(n, edges):
sort edges by weight ascending
parent = array [0, 1, 2, ..., n-1]
mst = empty list
for (u, v, w) in edges:
rootU = find(u)
rootV = find(v)
if rootU != rootV:
mst.append((u, v, w))
union(rootU, rootV)
if mst.size == n - 1:
break
return mst
You will add exactly edges if the graph is connected. The Union-Find operations ensure you never create a cycle.