1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow

Tutorial Playlist

58 Lessons
27

Prim's Algorithm in Data Structure: A Detailed Guide

Updated on 07/08/2024270 Views

Introduction

Data structures are necessary for keeping and organizing information in a computer system. They provide efficient storage, retrieval, and data manipulation in myriad computational tasks. Prim's Algorithm is a fundamental algorithm in data structures among several algorithms.

Prim's algorithm has been extensively applied since its introduction by Czech mathematician Vojtěch Jarník in 1930. It was later rediscovered and popularized by computer scientist Robert C. Prim in 1957. Its elegance and efficiency make it indispensable in network design, routing algorithms, and infrastructure optimization.

In this guide, let’s delve into the intricacies of Prim's algorithm within the context of data structures. We will explore its definition and implementation, shedding light on its applications in modern computational systems.

Overview

Prim's Algorithm aims to find the subset of edges that form a tree connecting all vertices of a weighted graph with the minimum total weight. This algorithm operates by iteratively selecting the shortest edge that connects a vertex in the tree to a vertex outside the tree until all vertices are included.

This iterative approach makes Prim’s Algorithm easy to understand and implement while also ensuring optimal performance in terms of time complexity. The beauty of Prim's Algorithm lies in its simplicity and efficiency. Let’s dive in!

What is Prim’s Algorithm

Prim's Algorithm is a fundamental algorithm used to find the Minimum Spanning Tree (MST) of a weighted graph. But what exactly does that mean? Let's break it down.

We shall start our discussion with graphs. In terms of computer science, the graph is defined as several connected vertices (known as nodes). Each edge has its associated cost or weight, signifying how much it will take to go from one vertex to another. Applications of graphs can be found everywhere, like social network analysis or computer networking

Now, what's a Minimum Spanning Tree (MST)?

The minimum spanning tree of a graph is a subset of edges that links all vertices with the least total weight possible and thus forms a cycle-free tree. 

Assume you have a network of cities, where each road has some distance (weight) associated with it. A Minimum Spanning Tree comprises the roads necessary to connect all the cities with the lowest sum total distances. It is just like trying to find the best way to link all towns without taking any extra miles.

So, how does Prim's Algorithm fit into all of this? And what exactly is the Prim’s algorithm

Prim's algorithm is a greedy algorithm, which means it makes locally optimal choices at each step with the hope of finding a globally optimal solution. In the context of finding a Minimum Spanning Tree, Prim's Algorithm starts with an arbitrary vertex and repeatedly adds the shortest edge that connects a vertex in the partially constructed MST to a vertex outside of it. This procedure continues until all vertices are represented in the MST.

So basically, Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and identifies the subset of edges that:

  • Forms a tree encompassing all vertices.
  • Yields the minimum sum of weights among all possible trees derived from the graph.

The Prim's algorithm time complexity is:

O(E log V)

This time complexity implies that its runtime grows in proportion to the number of edges (E) and vertices (V) in the graph.

Let me illustrate and explain Prim's algorithm with a simple example. Suppose you have a graph representing networks of cities between which you have roads of distinct lengths. Prim's Algorithm starts from an arbitrary city and incrementally builds up the Minimum Spanning Tree by adding any shortest road connecting one or more new cities to those already visited. This is repeated until every city is connected in such an efficient manner as possible.

How Does Prim’s Algorithm Work

Prim's algorithm works by constructing a Minimum Spanning Tree (MST) within a weighted graph in an orderly manner. Here are the prim's algorithm steps:

  • Initialization: You start by picking an arbitrary vertex from the graph as your MST’s initial point.
  • Expansion: You expand the MST step by step by adding the shortest side connecting a vertex to one that does not. This will entail continuously selecting the smallest weight edge connecting a vertex in MST to a vertex not yet chosen.
  • Greedy Approach: Prim’s Algorithm uses a greedy approach, implying that it always picks a locally optimum solution for each step. By choosing the shortest edge available at every iteration, its objective is to construct an MST with minimum total weight.
  • Priority Queue: Prim’s Algorithm often uses a priority queue data structure in order to pick the shortest edge at each step efficiently. This data structure for prim's algorithm allows you to quickly access and retrieve the edge with the lowest weight, thus facilitating greedy selection.

Example and illustration of Prim's Algorithm

Now, let’s illustrate Prim's Algorithm through a simple example.

This example demonstrates how to construct a Minimum Spanning Tree (MST) within a weighted graph. Consider the following graph:

 

We want to find the MST for this graph using Prim's Algorithm. Below is how it works:

Initialization: The process starts by choosing any vertex. Let us suppose A is the initial vertex for MST.

Expansion: Starting from A vertex, look at all edges connecting it: AB (with weight 2), AC (with weight 1), and AD (with weight 4). Choose the smallest edge in terms of weight, which is AC. Now, we have included Vertex C in the MST.

Next Iteration: In the next iteration, Consider all edges connected to these two vertices, A and C, as if they were our MST; such edges include AB (with weight 2), AD (with weight 4), and BC(weight 1). Pick out BC as it has a lower weight value compared to others, such as AD and AB. Thus, the B vertex is a part of MST.

Continuation: Moving forward, repeat this algorithm by examining edges associated with each of those already considered vertices and selecting an edge with minimum weight until all nodes have been covered in MST.

In this example, the MST constructed using Prim's Algorithm would look like this:

This MST has a total weight of 6, achieved by selecting edges AC, BC, and BD.

Implementation of Prim's Algorithm

Implementing Prim's Algorithm involves translating its steps into code, whether in pseudocode or a specific programming language like Python. Here's how you can approach it:

1. Prim's Algorithm Pseudocode

function Prim(graph):

#Create a set with no data to store the vertices in the minimum spanning tree.

mst = empty set

# Start the tree with the first vertex

startVertex = first vertex in graph

mst.add(startVertex)

# start the edges

edges = edges connected to startVertex

# Iterate till the minimum spanning tree

while vertices in mst are fewer than vertices in graph:

     # Find the minimum edge in the set of edges

     minEdge, minWeight = findMinEdge(edges)

     # Add the vertex to MST

mst.add(minEdge)

     # Add the edges connected to the vertex to the set of edges to consider

     for edgever in edges connected to minEdge:

         if edgever is not in mst:     

edges.add(edgever)

     # Remove the minimum edge  

edges.remove(minEdge)

# Return the minimum spanning tree as an array

return mst as an array

2. Implementation in Python

import heapq

def prim(graph):

MST = set()  # Initialize Minimum Spanning Tree

PQ = []  # Priority Queue to store vertices and their corresponding edge weights

start_vertex = list(graph.keys())[0]  # Choose an arbitrary starting vertex

visited = set()  # Set to keep track of visited vertices

visited.add(start_vertex)

for neighbor, weight in graph[start_vertex]:

heapq.heappush(PQ, (weight, start_vertex, neighbor))  # Add edges incident to start_vertex to PQ

while PQ:

     weight, source, target = heapq.heappop(PQ)  # Remove the vertex with the minimum edge weight from PQ

     if target not in visited:

MST.add((source, target, weight))

# Add the edge to MST

visited.add(target)

         for neighbor, weight in graph[target]:

             if neighbor not in visited:        

heapq.heappush(PQ, (weight, target, neighbor))  # Add new edges to PQ

return MST

# Example graph represented as adjacency list

graph = {

'A': [('B', 2), ('C', 1)],

'B': [('A', 2), ('C', 3), ('D', 3)],

'C': [('A', 1), ('B', 3), ('D', 4)],

'D': [('B', 3), ('C', 4)]

}

# Print the Minimum Spanning Tree

print(prim(graph))

This Python implementation utilizes a priority queue (heapq) to efficiently select edges with the minimum weight at each step. It iterates through the graph, adding vertices and their incident edges to the priority queue and then constructing the Minimum Spanning Tree accordingly.

Comparison of Prim's, Kruskal's, and Borůvka's Algorithms for Minimum Spanning Trees 

Several algorithms exist for finding Minimum Spanning Trees (MSTs) in a graph, each having its own approach and characteristics. Kruskal's Algorithm and Borůvka's Algorithm are two commonly used algorithms besides Prim’s algorithm.

In this comparison, we shall look at how Prim’s algorithm compares with Kruskal’s algorithm and Boruvka’s algorithm based on their important features and performance.

Feature

Prim's Algorithm

Kruskal's Algorithm

Borůvka's Algorithm

Time Complexity

O(V^2) with adjacency matrix, O(E log V) with heap

O(E log E) or O(E log V) with Union-Find Structure

O(E log V) or O(E log log V) with Union-Find Structure

Space Complexity

O(V)

O(V)

O(V)

Implementation Complexity

More straightforward, especially with a priority queue

Requires sorting edges, but simpler implementation

More complex due to simultaneous merges

Performance on Sparse Graphs

Less efficient due to potential quadratic time

More efficient due to sorting and Union-Find Structure

More efficient due to parallel edge merging

Performance on Dense Graphs

More efficient due to potential quadratic time

Less efficient due to sorting and Union-Find Structure

Less efficient due to multiple iterations

Handling Edge Weights

Efficient with both positive and negative weights

Efficient with positive weights, inefficient with negatives

Efficient with positive weights

Each algorithm has strengths and drawbacks, making it appropriate for a variety of applications. Prim's Algorithm is efficient on dense graphs with non-negative weights, Kruskal's Algorithm excels on sparse graphs with positive weights, and Borůvka's Algorithm is advantageous when parallel processing is possible.

The choice of algorithm depends on the graph's specific characteristics and the application's requirements.

Applications of Prim's Algorithm

Prim's Algorithm is widely used in various fields due to its simplicity and ability to construct Minimum Spanning Trees (MSTs) in graphs efficiently. The following are some important applications:

1. Laying Cables of Electrical Wiring

Prim's algorithm is often employed to lay cables for electrical wiring within infrastructure projects. This way, engineers can create an MST of regions that need electric interconnections so as to minimize the total length of the cable required, leading to a reduction in costs and network layout optimization.

2. Network Design

Prim's Algorithm has great significance when it comes to designing efficient network architectures for telecommunications and computer networking. Basically, this algorithm helps establish direct connections among nodes of a network while trying hard not to make the overall cost exceed the highest extent possible. For example, telecommunication companies use Prim’s Algorithm to construct networks of cell towers or fiber optic cables.

3. Designing Routing Protocols in Computer Networks

Prim's algorithm plays an important role in building routing protocols for computer networks. In other words, routing protocols can determine the shortest paths between nodes by constructing an MST on the network topology graph. Protocols such as OSPF (Open Shortest Path First) and IS-IS (Intermediate System to Intermediate System) use principles from Prim's Algorithms when calculating routes.

4. Vehicle Routing and Logistics

Prim's algorithm can be adapted to solve vehicle routing problems in logistics and transportation. By constructing an MST of delivery locations, logistics companies can optimize their delivery routes, minimizing fuel consumption and transportation costs.

5. Oil Pipeline Network Design

Prim's Algorithm is utilized in the design of oil pipeline networks to minimize the overall length of pipelines required to connect different oil fields, refineries, and distribution centers. This helps reduce transportation costs and the environmental impact of oil transportation.

Conclusion

In conclusion, Prim's Algorithm stands as a cornerstone in data structures and graph theory. It offers a powerful solution for constructing Minimum Spanning Trees (MSTs) in weighted graphs.

With its elegant simplicity and efficiency, Prim's Algorithm has found widespread applications across various domains, from network design and telecommunications to urban planning and logistics.

By understanding the mechanics and applications of Prim's Algorithm, you gain a valuable tool for optimizing connectivity and resource allocation in diverse real-world scenarios. Prim's Algorithm remains a fundamental algorithmic tool for driving efficiency and innovation in computational systems.

FAQs

  1. What is the Prim's algorithm?

Prim's algorithm is a method for finding the Minimum Spanning Tree (MST) of a weighted graph. It starts from an arbitrary vertex and grows the MST by iteratively adding the shortest edge connecting a vertex in the tree to a vertex outside of it.

  1. What is the difference between Prim's and Kruskal's algorithms?

The main difference lies in their approach. Prim's algorithm grows the Minimum Spanning Tree (MST) from a starting vertex, whereas Kruskal's algorithm builds the MST by selecting edges in increasing order of weight without necessarily considering connectivity to a specific vertex.

  1. Is Prim's algorithm the same as Dijkstra's? 

No, Prim's algorithm and Dijkstra's algorithm are different. Prim's algorithm finds the Minimum Spanning Tree (MST) of a weighted graph, while Dijkstra's algorithm finds the shortest path from a source vertex to all other vertices in a graph with non-negative edge weights.

  1. Is Prim's algorithm correct?

Yes, right is Prim’s algorithm. It always gives a Minimum Spanning Tree (MST) of a given weighted graph.

  1. Why is Prim's algorithm used?

Prim’s algorithm is used to find the Minimum Spanning Tree (MST) of a weighted graph that has various practical applications such as network design, infrastructure optimization, and routing protocols in computer networks.

  1. What is Prim's and Kruskal's algorithm?

Prim's and Kruskal's algorithms learn the weighted graph Minimum Spanning Tree (MST) equally. However, they differ in their approaches: Prim’s algorithm starts from a vertex and grows MST, while Kruskal's algorithm selects edges in increasing order of weight.

  1. Why is Prim's algorithm called greedy?

Prim’s algorithm is called greedy because it makes locally optimal choices at each step with the hope of finding a globally optimal solution. It selects the shortest edge available at each iteration, aiming to ultimately create an MST with the minimum total weight.

  1. What are the advantages of Prim's algorithm?

Prim’s algorithm has many benefits such as being simple, efficient, and capable of handling graphs with both positive and negative edge weights. Additionally, it guarantees that the resulting tree will always be connected forming a valid Minimum Spanning Tree (MST).

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...