DAA Chapter 3
DAA Chapter 3
Greedy Algorithms
1
CoSc3094 - DDU - 2024 G.C
Greedy Algorithm
▪ A greedy algorithm is an algorithmic paradigm that
follows the problem-solving heuristic of making the
locally optimal choice at each stage with the hope of
finding a global optimum.
− It doesn't worry whether the current best result will bring
the overall optimal result.
1. Kruskal's Algorithm
2. Prim's Algorithm
▪ Therefore, edges (h, i), (e, f), (b, h), and (d, f) are
discarded. This is because the vertices of each edges
belongs to the same tree.
2. Find all the edges that connect the tree to new vertices,
find the minimum and add it to the tree
• The inputs taken by the algorithm are the graph G {V, E},
where V is the set of vertices and E is the set of edges, and
the source vertex S.
• Application:
– To find the shortest path
– In social networking applications
– In a telephone network
– To find the locations in the map
CoSc3094 - DDU - 2024 G.C 40
Dijkstra's Algorithm: Example
▪ Find the shortest path using Dijkstra’s algorithm for the
graph given below with S as the arbitrary source.
Vertex S A B C D E
Distance 0 ∞ ∞ ∞ ∞ ∞
• Visited = {S, A, E, D}
Vertex S A B C D E
Distance 0 6 15 12 8 7
CoSc3094 - DDU - 2024 G.C 46
Dijkstra's Algorithm: Example
Solution: Vertex S A B C D E
Distance 0 6 15 11 8 7
▪ Step 5
• Recalculate the distances of unvisited vertices and if the
distances minimum than existing distance is found, replace
the value in the distance array.
• S → C = S → E + E → C = 7 + 5 = 12
• S → C = S → D + D → C = 8 + 3 = 11
• distance[C] = minimum (12, 11) = 11
• S → B = S → A + A → B = 6 + 9 = 15
• S → B = S → D + D → C + C → B = 8 + 3 + 12 = 23
• distance[B] = minimum (15, 23) = 15
• Visited = {S, A, E, D, C}
CoSc3094 - DDU - 2024 G.C 47
Dijkstra's Algorithm: Example
Solution:
▪ Step 6
• The remaining unvisited vertex in the graph is B with the
minimum distance 15, is added to the output spanning
tree.
• Visited = {S, A, E, D, C, B}