Prim's Algorithm in Data Structure: Example & Complexity
Understand Prim's Algorithm with a simple weighted graph, pictorial diagrams, step-by-step MST calculation, C program, dry run and interactive visual learning.
Imagine your college has six buildings. All these buildings need to be connected using internet cables.
There are different possible cable connections between these buildings.
Some connections cost less, while others cost more.
Our goal is to connect all six buildings without using unnecessary cables and with the lowest possible total cost.
How can we select the right connections?
This is where Prim's Algorithm helps us.
Prim's Algorithm is an important greedy algorithm used to find a Minimum Spanning Tree in a connected, weighted, undirected graph.
Students often remember that Prim's Algorithm chooses the minimum edge, but become confused about which minimum edge should be selected.
In this chapter, we will understand that selection rule using a clear diagram, a step-by-step dry run, a working C program and a live visualizer.
Prim's Algorithm is a greedy graph algorithm that finds a Minimum Spanning Tree (MST). It begins with one vertex and repeatedly selects the minimum-weight edge that connects the current tree to a new vertex.
The process continues until all vertices are included in the tree.
With an Adjacency Matrix, a standard implementation takes O(V²) time.
What Is Prim's Algorithm in Data Structure?

Prim's Algorithm is a greedy algorithm that finds a Minimum Spanning Tree of a connected, weighted, undirected graph.
A Minimum Spanning Tree connects all vertices, does not contain a cycle and has minimum total edge weight.
Prim's Algorithm starts from any one vertex and keeps growing a single tree.
At each step, it chooses the cheapest connection from the current tree to a vertex not yet included.
Three Main Rules of Prim's Algorithm
Choose a starting vertex, such as A, and begin building the tree.
Choose the minimum-weight edge connecting the current tree to a new vertex.
Repeat until every vertex belongs to the tree and V−1 edges are selected.
Why Is Prim's Algorithm Called Greedy?
A greedy algorithm makes the best valid local choice at each step.
Prim's Algorithm chooses the cheapest edge that can extend its current tree.
By following this rule correctly, the algorithm produces an MST.
Memory Trick: Prim = Pick one new vertex using the cheapest valid connection from the current tree.
Prim's Algorithm Example with Weighted Graph
We will use a new weighted graph with six vertices.
The vertices are A, B, C, D, E and F.
Every edge has a weight that represents its cost.
Every line represents an edge. The number written near it represents its weight.
Edge Weight Table
| Edge | Weight | Connection |
|---|---|---|
| A–B | 4 | A to B |
| A–C | 3 | A to C |
| B–C | 1 | B to C |
| B–D | 7 | B to D |
| C–D | 6 | C to D |
| C–E | 10 | C to E |
| D–E | 2 | D to E |
| D–F | 9 | D to F |
| E–F | 5 | E to F |
Our goal is to select five edges that connect all six vertices without cycles, with the minimum possible total weight.
How Does Prim's Algorithm Select the Next Edge?
This is the most important part of Prim's Algorithm.
Students sometimes think Prim's Algorithm always selects the globally smallest edge in the entire graph.
That is not the correct rule.
Prim's Algorithm selects the cheapest edge that connects the current growing tree to a new vertex.
Example: Start from A
Initially, only A belongs to the tree.
The edges connected to A are:
Notice that edge B–C has weight 1 and D–E has weight 2.
We cannot choose either as our first edge from A because neither has an endpoint in the current tree containing only A.
After adding C, edge B–C becomes a valid candidate. We can now select it.
Golden Rule: One endpoint must already belong to the current tree, and the other endpoint must be outside it.
Prim's Algorithm Step-by-Step Example with MST Calculation
We will start Prim's Algorithm from vertex A.
At each step, we check valid outgoing edges, select the cheapest one and update the total weight.
Begin with only vertex A in the tree.
No edge has been selected yet.
From A, available connections are: AB(4) and AC(3).
AC has smaller weight, so choose AC.
Now the tree contains A and C.
The outgoing candidates include AB(4), CB(1), CD(6) and CE(10).
CB has the smallest weight. Choose CB.
The current tree contains A, B and C.
The remaining outside vertices are D, E and F.
Valid outgoing candidates include BD(7), CD(6) and CE(10).
The cheapest valid edge is CD(6).
After D joins the tree, DE(2) becomes a valid candidate.
This edge is cheaper than the remaining outgoing connections.
Therefore, select DE(2).
Only vertex F remains outside the tree.
There are two available connections: DF(9) and EF(5).
Select EF(5) because it is cheaper.
Prim's Algorithm Dry Run Table
| Step | Selected Edge | Weight | Running Total | Vertices in Tree |
|---|---|---|---|---|
| Start | — | 0 | 0 | A |
| 1 | A–C | 3 | 3 | A, C |
| 2 | C–B | 1 | 4 | A, C, B |
| 3 | C–D | 6 | 10 | A, C, B, D |
| 4 | D–E | 2 | 12 | A, C, B, D, E |
| 5 | E–F | 5 | 17 | A, C, B, D, E, F |
Final Minimum Spanning Tree
Selected Edges = 5. All 6 vertices are connected and no cycle is formed.
Key Array, Parent Array and Visited Array in Prim's Algorithm
When we implement Prim's Algorithm in C or another language, we need to remember some information about the vertices.
Three useful arrays are Key, Parent and inMST.
1. Key Array
The Key array stores the minimum currently known edge weight connecting each outside vertex to the growing tree.
Initially, all keys are infinity except the starting vertex, whose key is zero.
2. Parent Array
The Parent array stores the vertex offering the current cheapest connection.
For example, if key[B] becomes 1 because of C–B, then parent[B] = C.
3. inMST Array
The inMST array tells us whether a vertex has already been included in the growing tree.
Example of Key Updates
| After Including | Important Key Updates |
|---|---|
| A | B = 4, C = 3 |
| C | B = 1, D = 6, E = 10 |
| B | No smaller connection replaces D = 6 |
| D | E = 2, F = 9 |
| E | F = 5 |
Remember: Key stores a connection cost, not the total distance from the starting vertex. That is an important difference between Prim's and Dijkstra's algorithms.
Prim's Algorithm Steps and Pseudocode
Prim's Algorithm in Easy Steps
- Choose a starting vertex.
- Set the starting vertex key to zero and other keys to infinity.
- Select the outside vertex having the smallest key.
- Add its connecting edge to the MST, except for the starting vertex.
- Check all neighbours of the newly included vertex.
- If a cheaper connection is found, update the neighbour's key and parent.
- Repeat until every vertex belongs to the MST.
Prim's Algorithm Pseudocode
Prim(Graph, start):
for every vertex v:
key[v] = INFINITY
parent[v] = NONE
inMST[v] = false
key[start] = 0
repeat V times:
u = outside vertex
with smallest key
if key[u] == INFINITY:
report disconnected graph
inMST[u] = true
for every neighbour v of u:
if v not in MST
and weight(u,v) < key[v]:
key[v] = weight(u,v)
parent[v] = u
return parent and selected edges
Why Does Prim's Algorithm Avoid Cycles?
Each step adds one vertex that was not previously part of the tree.
Since the new edge connects the tree to an outside vertex, it cannot create a cycle.
This continues until all vertices have been included.
Prim's Algorithm in C with Example and Output
Now let us write a complete C program for Prim's Algorithm.
This program uses an Adjacency Matrix and the Key, Parent and inMST arrays.
It uses the same six-vertex weighted graph explained above.
In this program, zero means there is no edge, since all actual example edge weights are positive.
Complete Prim's Algorithm C Program
#include <stdio.h>
#include <limits.h>
#define V 6
int main(void) {
/* Weighted adjacency matrix */
const int graph[V][V] = {
{0,4,3,0,0,0},
{4,0,1,7,0,0},
{3,1,0,6,10,0},
{0,7,6,0,2,9},
{0,0,10,2,0,5},
{0,0,0,9,5,0}
};
int key[V];
int parent[V];
int inMST[V] = {0};
/* Initialization */
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
parent[i] = -1;
}
/* Start from vertex A */
key[0] = 0;
int total = 0;
int edges = 0;
puts("Prim's Algorithm (start A)");
/* Select all vertices */
for (int step = 0; step < V; step++) {
int u = -1;
/* Find minimum key vertex */
for (int i = 0; i < V; i++) {
if (
!inMST[i] &&
(
u == -1 ||
key[i] < key[u]
)
) {
u = i;
}
}
/* Disconnected graph check */
if (
u == -1 ||
key[u] == INT_MAX
) {
puts(
"No MST: graph is disconnected."
);
return 1;
}
/* Include vertex in MST */
inMST[u] = 1;
/* Add its connecting edge */
if (parent[u] != -1) {
printf(
"%c-%c : %d\n",
'A' + parent[u],
'A' + u,
key[u]
);
total += key[u];
edges++;
}
/* Update neighbours */
for (int v = 0; v < V; v++) {
if (
graph[u][v] > 0 &&
!inMST[v] &&
graph[u][v] < key[v]
) {
key[v] = graph[u][v];
parent[v] = u;
}
}
}
/* Final result */
printf(
"Selected edges: %d\n"
"Minimum total weight: %d\n",
edges,
total
);
return 0;
}
Output of Prim's Algorithm in C
Prim's Algorithm (start A)
A-C : 3
C-B : 1
C-D : 6
D-E : 2
E-F : 5
Selected edges: 5
Minimum total weight: 17
Explanation of the C Program
1. Adjacency Matrix
The graph array stores the weights of all available edges.
2. Key Array
The key array remembers the cheapest known connection for each outside vertex.
3. Parent Array
The parent array records which vertex provides that cheapest connection.
4. inMST Array
The inMST array prevents previously included vertices from being selected again.
5. Find Minimum Key
In each iteration, the program scans all outside vertices and selects the minimum key.
6. Update Connections
Once a vertex joins the tree, its neighbours are checked for cheaper connections.
7. Display MST
The selected edges are printed with their weights.
The program then displays the total number of edges and minimum weight.
Program Verification: This C program was compiled using GCC with C11, Wall, Wextra and strict warning checks. The result is five MST edges with total weight 17.
Run Prim's Algorithm in VS Code
- Open Visual Studio Code.
-
Create a file named
prim55.c. - Paste the complete C program.
- Open the integrated terminal.
- Compile with GCC.
- Run the executable.
gcc -std=c11 -Wall -Wextra -Werror -pedantic prim55.c -o prim55
.\prim55.exe
Interactive Prim's Algorithm MST Visualizer
Now you can practise Prim's Algorithm using a live weighted graph.
Choose the starting vertex and click Next Step.
The visualizer shows which edge is selected, which vertices are already in the tree and how the total MST weight changes.
Prim's Algorithm Visual Lab
Learn by selecting one edge at a time. All edge weights are fixed to match the example above.
Green edges are selected. Yellow dashed edges are currently available candidates.
Live Key and Parent Table
| Vertex | Key | Parent | Status |
|---|---|---|---|
| A | 0 | — | In MST |
| B | 4 | A | Waiting |
| C | 3 | A | Waiting |
| D | ∞ | — | Waiting |
| E | ∞ | — | Waiting |
| F | ∞ | — | Waiting |
Start from vertex A. The first candidates are AB(4) and AC(3).
Practice 1: Start from A and complete all five edge selections.
Practice 2: Change the starting vertex to D. Observe how the edge-selection order changes.
Practice 3: Check whether the final MST cost remains 17.
Prim's Algorithm Time and Space Complexity
The time complexity of Prim's Algorithm depends on how the graph is stored and how we select the minimum key.
Prim's Algorithm Using Adjacency Matrix
In a simple Adjacency Matrix implementation, finding the minimum key vertex requires scanning vertices.
Updating neighbour keys also requires scanning a matrix row.
Prim's Algorithm Using Binary Heap
For larger sparse graphs, Prim's Algorithm can use an Adjacency List and a Min Priority Queue.
A Binary Heap helps efficiently select a vertex with minimum key.
Complexity Comparison Table
| Implementation | Time Complexity | Typical Use |
|---|---|---|
| Adjacency Matrix | O(V²) | Dense graphs |
| Adjacency List + Binary Heap | O((V+E) log V) | Sparse graphs |
Best, Average and Worst Case
For the matrix-based version shown above, the algorithm scans vertices and matrix rows in each iteration.
Therefore, its standard asymptotic running time is O(V²).
Heap-based performance depends on the number of vertices and edges.
Exam Tip: If the question asks the time complexity of Prim's Algorithm, mention the implementation. Do not assume one bound applies to every version.
Prim's Algorithm vs Kruskal's Algorithm
Prim's and Kruskal's are both greedy algorithms used for Minimum Spanning Trees.
Their main difference is how they select edges.
| Feature | Prim's Algorithm | Kruskal's Algorithm |
|---|---|---|
| Approach | Grows one tree | Connects separate groups |
| Starting Vertex | Used | Not required |
| Edge Selection | Cheapest edge leaving current tree | Cheapest available edge that avoids cycles |
| Main Data Structure | Key array / Priority Queue | Sorted edges / DSU |
| Cycle Prevention | Adds one outside vertex | Checks whether endpoints are already connected |
| Result | Minimum Spanning Tree | Minimum Spanning Tree |
Prim's Algorithm vs Dijkstra's Algorithm
Students sometimes confuse Prim's Algorithm with Dijkstra's Algorithm because both can use a Priority Queue and a Key-like array.
However, their goals are different.
Prim's Algorithm finds a Minimum Spanning Tree.
Dijkstra's Algorithm finds shortest-path distances from a starting vertex in graphs with non-negative edge weights.
Memory Trick: Prim = Minimum network connection cost. Dijkstra = Minimum path distance from the source.
Applications of Prim's Algorithm in Data Structure
1. Computer Network Connections
Prim's Algorithm can help model the minimum-cost problem of connecting network locations.
2. Cable Network Planning
Different cable routes can have different installation costs.
An MST can identify a minimum-weight set of connections in a simplified model.
3. Electrical Networks
MST algorithms can be useful in planning connected layouts where edges have costs.
4. Road Network Models
Cities may be represented as vertices and possible roads as weighted edges.
An MST connects the cities with minimum total edge weight.
5. Clustering
Minimum Spanning Trees can also be used in some clustering techniques to study relationships between data points.
Important: Real engineering networks may require reliability, extra connections or capacity constraints. An MST is the minimum-weight tree for the model, not automatically a complete real-world design.
Common Mistakes in Prim's Algorithm
| Mistake | Correct Concept |
|---|---|
| Always choosing the globally cheapest edge | Choose the cheapest edge connecting the current tree to an outside vertex. |
| Including an already selected vertex | Only a new outside vertex may join the tree. |
| Choosing V edges | An MST contains V−1 edges. |
| Confusing Key with total source distance | Key is the cheapest edge joining a vertex to the current tree. |
| Ignoring disconnected graphs | A disconnected graph has no single spanning tree covering all vertices. |
| Writing O(V+E) for matrix-based Prim | The standard matrix version takes O(V²) time. |
| Assuming the same selection order for every start | The order may change with the starting vertex. |
Important Prim's Algorithm Questions with Answers
These original exam-style questions help students prepare for BCA, MCA and Data Structure examinations.
1. Define Prim's Algorithm.
Prim's Algorithm is a greedy algorithm that finds a Minimum Spanning Tree of a connected, weighted, undirected graph.
2. Why Is Prim's Algorithm Greedy?
It selects the minimum-weight valid edge at each step to grow the current tree.
3. What Is an MST?
An MST is a connected, cycle-free spanning tree having minimum total edge weight.
4. Explain the Working of Prim's Algorithm.
Prim's Algorithm begins with a starting vertex.
It repeatedly selects the minimum-weight edge that connects the current tree to a new vertex.
The process continues until all vertices are included.
The final tree contains V−1 edges and has minimum total weight.
5. Explain the Role of Key and Parent Arrays.
The Key array stores the minimum known connection cost for an outside vertex.
The Parent array stores the vertex offering that cheapest connection.
These arrays help the algorithm build the MST.
6. Explain Prim's Algorithm with Example, C Program and Time Complexity.
Prim's Algorithm is a greedy method used to construct a Minimum Spanning Tree.
It starts from any one vertex and grows the tree by repeatedly selecting the cheapest edge leading to a new vertex.
For our example, starting from A, the selected edges are:
AC(3), CB(1), CD(6), DE(2) and EF(5).
Therefore, the total MST weight is 17 units.
A standard Adjacency Matrix implementation uses Key, Parent and inMST arrays.
Its time complexity is O(V²).
With an Adjacency List and Binary Heap, a common bound is O((V+E) log V).
Prim's Algorithm MCQs and Practice Questions
Q1. Prim's Algorithm Is Based on Which Technique?
A. Dynamic Programming
B. Greedy Approach
C. Divide and Conquer
D. Backtracking
Show Answer
B. Greedy Approach. Prim's Algorithm selects the cheapest valid edge at every step.
Q2. How Many MST Edges Are Needed for 6 Vertices?
Show Answer
V−1 = 6−1 = 5 edges.
Q3. Which Edge Is Selected First from A?
Show Answer
A–C with weight 3, because AC(3) is cheaper than AB(4).
Q4. What Is the Total MST Weight?
Show Solution
3 + 1 + 6 + 2 + 5 = 17 units.
Q5. Can Prim's Algorithm Start from Any Vertex?
Show Answer
Yes. In a connected, weighted, undirected graph, Prim's Algorithm may start from any vertex.
The selection order may change, but the minimum total MST weight remains the same.
Q6. What Happens If the Graph Is Disconnected?
Show Answer
A single MST covering every vertex cannot exist. The graph can instead have a Minimum Spanning Forest.
FAQs About Prim's Algorithm in Data Structure
What is Prim's Algorithm in simple words?
Prim's Algorithm connects all vertices by repeatedly choosing the cheapest edge from the growing tree to a new vertex.
What is the main purpose of Prim's Algorithm?
Its main purpose is to find a Minimum Spanning Tree of a connected, weighted, undirected graph.
Does Prim's Algorithm use Greedy Approach?
Yes. It makes the cheapest valid local choice while growing the tree.
What is Prim's Algorithm time complexity?
O(V²) for a standard matrix implementation. A heap-based version can take O((V+E) log V).
Can Prim's Algorithm have negative edge weights?
Yes. The MST problem allows negative edge weights. A correct implementation must represent absent edges separately.
Is Prim's Algorithm the same as Kruskal's?
No. Both find an MST, but Prim grows one tree, while Kruskal selects edges in sorted order and avoids cycles.
Can Prim's Algorithm start from any vertex?
Yes. The starting vertex can change, but the final minimum MST weight remains the same.
How is Prim's Algorithm different from Dijkstra's?
Prim minimizes total spanning-tree weight. Dijkstra minimizes shortest-path distances from a source.
Prim's Algorithm Quick Revision Notes
One-Line Memory Trick: Prim starts with one vertex and grows one minimum-cost connected tree.
Conclusion
Prim's Algorithm is an important greedy algorithm used to find a Minimum Spanning Tree.
It begins with a single vertex and grows one tree by choosing the cheapest valid edge at every step.
The most important thing to remember is that the selected edge must connect the current tree to a new vertex.
For semester examinations, practise drawing weighted graphs, calculating the MST, writing Key and Parent array updates and running the C program.
Chapter 55 — Completed
