prim's algorithm
a greedy algorithm to find an mst in a given undirected weighted graph.
a basic implementation (better complexity can be achieved with a better implementation, proposed later in this note):

a basic implementation (better complexity can be achieved with a better implementation, proposed later in this note):
at each step of prim's algorithm the graph
is a tree
is also a subgraph of an mst of
it follows trivially from the code.
proof by induction on the number of iterations in the loop
base step: immediately after initialization,
, at this point, the graph
contains a single arbitrary vertex of
and contains no edges, each mst of
contains all vertices in
, so the claim is correct in this case.
induction hypothesis: assume that after the addition of
vertices to
and
edges to
, the tree
is a subgraph of an mst of
which we shall call
. let
be the minimum edge in
that the algorithm adds to
such that
.
case 1:
, the algorithm "picked"
as the mst, the claim's correctness follows trivially.
case 2:
, the algorithm "picked" another mst of
, in this case we need to show that there is another mst of
, which we call
, such that
.
is an mst of
, which means that
contains a path
from
to
. and since
, we know the path
crosses from
to
, which means that
must contain an edge
such that
.
let
be the graph whose set of edges
is received by removing
from
and adding
, i.e.
. according to spanning tree lemma 1,
is a spanning tree of
. we can see that trading
for
results in a different mst of
. at the moment
is added to
, the edges
and
are both in
and the algorithm chose
before
which means
which means
, but on the other side,
is an mst of
and so
. and so
, and
, i.e.
is another mst of
. during the
-th iteration of the loop, the algorithm "chooses" between
and
, and
and
.
base step: immediately after initialization,
induction hypothesis: assume that after the addition of
case 1:
case 2:
let
prim's algorithm computes an mst of the input graph.
according to lem-prim-1, at the end of each iteration in the loop,
is included in the mst of the input graph, at the end of the
-th iteration,
would contain
vertices which means its an mst of
.
improvements in the algorithm:
given that
is the cut set, the time complexity for finding the minimal edge would be
and since
contains duplicate edges, consider the edges
, the time complexity can be
, we reduce this by defining
such that
is the minimal edge that connects
to a vertex in
, if there isnt such a vertex then
, the minimum edge in
would be included in
, and
. we propose a more efficient version of the algorithm that uses this idea to achieve
complexity:

given that
the time complexity of this algorithm is 