Skip to content

Prim's algorithm

Prim's algorithm is a greedy algorithm used to find the Minimum Spanning Tree in a graph.

It works well for dense graphs.

![Animation of Prim's algorithm on a graph](../assets/prim.gif 'Prim's algorithm - Wikipedia')

Algorithm

  1. Initialize the tree: chose the root node, which is a single vertex chosen arbitrarily from the graph.
  2. Grow the tree by one edge, by choosing one with the minimum weight (e.g. distance).
  3. Repeat step 2, until all vertices are in the tree.

Complexity

Prim algorithm complexity can change depending of the data structure used.

OperationArrayListTreeHeapFibonacci heap
InsertO(1)O(1)O(logn)O(logn)O(1)
Access minimumO(n)O(n)O(logn)O(1)O(1)
Delete minimumO(n)O(n)O(logn)O(logn)O(logn) (amorti)
Decreases keyO(1)O(1)O(logn)O(logn)O(1) (amorti)

Resources