{"id":81061,"date":"2021-06-23T09:00:10","date_gmt":"2021-06-23T03:30:10","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81061"},"modified":"2021-06-23T09:00:10","modified_gmt":"2021-06-23T03:30:10","slug":"greedy-algorithm","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/","title":{"rendered":"Greedy Algorithm with Applications"},"content":{"rendered":"<p>We encounter various types of computational problems each of which requires a different technique for solving. A problem that requires a maximum or minimum result is the optimization problem.<\/p>\n<p>There are broadly 3 ways to solve optimization problems:<\/p>\n<p>1. The greedy method<\/p>\n<p>2. Dynamic programming<\/p>\n<p>3. Branch and bound technique<\/p>\n<p>This article will cover the greedy method, properties of greedy algorithms and the steps to implement the greedy method over any problem.<\/p>\n<h3>What is Greedy Algorithm?<\/h3>\n<p>It simply means to pick up a choice\/solution that seems the best at the moment ( being greedy).\u00a0This technique is best suited when we want an immediate situation.\u00a0It helps to solve optimization problems i.e. which gives either minimum results or maximum results.<\/p>\n<p>A solution satisfying the condition in the problem is a feasible solution. The solution having minimum cost out of all possible feasible solutions is the optimal solution i.e. it is the best solution.<\/p>\n<p>The goal of the greedy algorithm is to find the optimal solution. There can be only 1 optimal solution.<\/p>\n<p><strong>For Example:<\/strong><\/p>\n<p>Let us consider the example of the container loading problem.<\/p>\n<p>In a container loading problem, a large ship is loaded with cargo. The cargo has containers of equal sizes but different weights. The cargo capacity is of the ship is cp.<\/p>\n<p>We need to load the containers in the ship in such a way that the ship has maximum containers.<\/p>\n<p>For example, let us say there are a total of 4 containers with weights: w1=20, w2=60, w33=40, w4=25.<\/p>\n<p>Let cp = 80. Then, to load maximum containers we will load container-1,3,4.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81208\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image.jpg\" alt=\"Greedy Algorithm\" width=\"650\" height=\"420\" \/><\/a><\/p>\n<p>We will load the containers in the order of increasing weights so that maximum containers load inside the ship. Here, the order of loading is container1\u2192container4\u2192container3.<\/p>\n<h3>History of Greedy Algorithm<\/h3>\n<p>The greedy algorithm was first coined by the Dutch computer scientist and mathematician Edsger W. Dijkstra when he wanted to calculate the minimum spanning tree. The major purpose of many greedy algorithms was to solve graph-based problems.<\/p>\n<p>The greedy algorithms first started coming into the picture in the 1950s. The then scientists, Prim and Kruskal also achieved the optimization techniques for minimizing the costs of graphs during that decade.<\/p>\n<p>A few years later, in the 1970s, many American researchers proposed a recursive strategy for solving greedy problems. In 2005, the NIST records registered the greedy paradigm as a separate optimization strategy.<\/p>\n<p>Since then, the greedy algorithm has been extensively in use in multiple fields including the web protocols such as the open-shortest-path-first (OSPF) and many other network packet switching protocols.<\/p>\n<h3>Working of Greedy Algorithm<\/h3>\n<p>The greedy algorithm works in various stages and considers one input at a time while proceeding.\u00a0At each stage, we try to find a feasible solution for our problem, a solution that is good for the algorithm at that point.\u00a0This means that we make a locally optimal choice for each sub-task.\u00a0These local optimal choices eventually lead us to the global optimal choice for our problem which we call the final optimal solution.<\/p>\n<p>The pseudo-code for the simplest greedy algorithm is shown below:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">ALgorithm Greedy(A,n)\n{\n    solution := \u03d5; \/\/Initializing the solution\n    for i:= 1 to n do\n    {\n        x := select(A);\n        if Feasible(solution,x) then\n            solution := Union(solution, x);\n    }\n    return solution;\n}\n<\/pre>\n<p>Here, A = an array of size n.<\/p>\n<p>The select function takes an input from the array and removes it. We assign this selected input value to x.<\/p>\n<p>Feasible is the boolean function that decides whether we can include x in the final solution vector or not. A good greedy algorithm has a proper implementation of select, Feasible and Union.<\/p>\n<h3>Properties required for the Greedy Algorithm<\/h3>\n<p>There are many techniques to solve a problem. Out of these many techniques, we have optimization techniques for a particular set of problems. Out of optimization techniques as well, there are multiple choices.<\/p>\n<p>So, how do we know that when to use and when not to use the greedy method as an optimization algorithm.<\/p>\n<p>For this purpose, we will check the properties of the algorithm. If the following two properties hold, we will use the greedy approach or other approaches.<\/p>\n<h4>1. Greedy choice property<\/h4>\n<p>To reach the final optimal solution or the globally optimal solution, we find locally optimal solutions(the best at that moment) for each sub-task.<\/p>\n<h4>2. Optimal sub-programs<\/h4>\n<p>A solution to the subproblem of an optimal solution is also always optimal.<\/p>\n<h3>Characteristic of a Greedy Approach<\/h3>\n<p>1. In the greedy method, we divide the main problem into sub-problems and solve each of them recursively.<\/p>\n<p>2. The greedy method maximizes the resources in a given time constraint.<\/p>\n<p>3. There is a cost and value attribution attached to these resources.<\/p>\n<h3>Steps to achieve Greedy Algorithm<\/h3>\n<h4>1. Feasible<\/h4>\n<p>The greedy algorithm proceeds by making feasible choices at each step of the whole process. Feasible choices are those which satisfy all the algorithmic constraints.<\/p>\n<h4>2. Local optimal choice<\/h4>\n<p>Choose what is best at the given time i.e. make locally optimal choices while preceding through the algorithm.<\/p>\n<h4>3. Unalterable<\/h4>\n<p>We cannot alter any sub-solution at any subsequent point of the algorithm while execution.<\/p>\n<h3>When to use Greedy Algorithm?<\/h3>\n<p>Greedy algorithms always choose the best possible solution at the current time. This sometimes leads to overall bad choices and might give worst-case results.<\/p>\n<p>For example, Suppose we wish to reach a particular destination and there are different paths for it, as shown below:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image02-1.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81211\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image02-1.jpg\" alt=\"Greedy method\" width=\"420\" height=\"420\" \/><\/a><\/p>\n<p>Here, following path \u2018A\u2019 will cost us 50, path \u2018B\u2019 will cost 8(minimum) and path \u2018C\u2019 will cost us 80.<\/p>\n<p>If we follow the greedy approach, we will first move from starting point to node \u2018C\u2019 because it has the minimum cost at that point. But in reality, this path has the maximum total cost. However, we were not able to detect it at the first step.<\/p>\n<p>Following the greedy method will cost us the maximum here i.e. 80. In such cases, the greedy approach might not give optimal results.<\/p>\n<p>So the question arises- When to use the greedy approach.<\/p>\n<p>We use this technique because it gives optimal results in many cases by just making \u2018layman moves\u2019. We also prefer greedy methods whenever we are sure that they will provide us with good approximations. In such cases, the greedy approach proves to be very effective as it is cheaper and faster.<\/p>\n<h3>Advantages of Greedy Algorithm<\/h3>\n<p>1. It is a highly optimized and one of the most straightforward algorithms.<\/p>\n<p>2. This algorithm takes lesser time as compared to others because the best solution is immediately reachable.<\/p>\n<p>3. In the greedy method, multiple activities can execute in a given time frame.<\/p>\n<p>4. We don\u2019t need to combine the solutions of sub-problems, as it automatically reaches the optimal solution.<\/p>\n<p>5. The algorithm is easy to implement.<\/p>\n<h3>Applications of Greedy Method<\/h3>\n<p>There are multiple applications of the greedy technique such as:<\/p>\n<h4>1. CPU Scheduling algorithms<\/h4>\n<p>CPU scheduling is a process that allows and schedules more than one processes in a CPU at a time so that there is maximum utilization of the CPU.<\/p>\n<p>This usually happens when one process is on hold due to the unavailability of resources, and to avoid CPU time wastage, we schedule a new process for the time.<\/p>\n<p>Multiple algorithms help in CPU scheduling and they make use of the greedy approach. The purpose of these algorithms is to maximize CPU utilization and minimize the time taken by a process to execute.<br \/>\nThere are various types of scheduling algorithms:<\/p>\n<h5>a. First come first serve<\/h5>\n<p>As the name suggests, it schedules processes based on first come first serve. It is a non-preemptive algorithm.<\/p>\n<h5>b. Shortest job first<\/h5>\n<p>It is both preemptive as well as non-preemptive scheduling algorithm. In this algorithm, we give the highest priority to process with the lowest burst time. Its preemptive version is known as the Shortest job first algorithm.<\/p>\n<h5>c. Priority scheduling<\/h5>\n<p>It is both preemptive or non-preemptive. In this technique, we assign priority to every process and then execute in the priority order. It mostly uses a priority queue for execution.<\/p>\n<h5>d. Round-robin scheduling<\/h5>\n<p>In this algorithm, we assign a fixed time slot to each process. If the process does not execute completely in that time slot, it will complete its remaining execution in the next rounds. It is preemptive.<\/p>\n<h5>e. Multiple level queue schedule<\/h5>\n<p>This is also a priority-based algorithm. It maintains multiple queues for the processes with different priorities.<\/p>\n<h4>2. Minimum spanning trees<\/h4>\n<p>A minimum spanning tree is a subset of a connected, weighted undirected graph that connects all the vertices without cycle. In MST, the total weight of all the edges is minimum.<\/p>\n<h4>3. Dijkstra shortest path algorithm<\/h4>\n<p>This algorithm is used to find the shortest path between two vertices in a graph in such a way that the sum of weights between the edges is minimum. All those algorithms in which we need to maximize or minimize something make use of the greedy approach.<\/p>\n<h4>4. Fit algorithm in memory management<\/h4>\n<p>This algorithm allocates different memory blocks to the processes in an operating system.<\/p>\n<p>In the fit algorithm, we make use of a pointer to keep track of all memory blocks available to us. The pointer also decides whether to accept or reject the request for memory block allocation for any incoming process. It makes this decision depending on three different fit memory management algorithms:<\/p>\n<h5>a. First fit algorithm<\/h5>\n<p>The pointer allocates that memory block to the process which it first finds to be sufficient for the process.<\/p>\n<h5>b. Best fit algorithm<\/h5>\n<p>The algorithm allocates the minimum sufficiently available memory block to the process.<\/p>\n<h5>c. Worst fit algorithm<\/h5>\n<p>It allocates the largest sufficient memory block available in the memory.<\/p>\n<h4>5. Travelling salesman problem<\/h4>\n<p>This is one of the standard problems that a greedy algorithm solves. In this problem, our objective is to make use of the greedy technique to find the shortest possible path. The objective is to visit each city exactly once and then return to the initial starting point.<\/p>\n<h4>6. Fractional knapsack problem<\/h4>\n<p>It is an optimization problem. In the fractional knapsack problem, we try to find a subset of items out of the total possible set of items. We ensure that their total weight is less than or equal to a given limit according to the problem. We also ensure that their value is maximum.<\/p>\n<h4>7. Egyptian fraction<\/h4>\n<p>It is a finite sum of unique distinct fractions. We can represent every positive fraction as a sum of unique unit fractions which we call the Egyptian fraction.<\/p>\n<h4>8. Bin packing problem<\/h4>\n<p>In the bin packing problem, we have a finite number of bins of fixed volume. We pack items of different volumes into those bins in such a way that we use the minimum number of bins.<\/p>\n<h3>Limitations of Greedy Algorithm<\/h3>\n<p>The greedy method works by finding the best possible outcome at every step of the algorithm. This sometimes leads to inaccurate results.<\/p>\n<p>For example, suppose we wish to find the longest path in the following graph:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image03.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81210\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image03.jpg\" alt=\"Limitation of Greedy Algorithm\" width=\"700\" height=\"420\" \/><\/a><\/p>\n<p>If we follow the greedy approach, we will make the best possible choice at every node.\u00a0In that case, the path will come out to be: 12\u219216\u21926\u219235 which comes out to be 69.<\/p>\n<p>However, in reality, the actual longest path is 12\u21924\u219222\u219298 which comes out to be 136. Here, achieving 136 is impossible using the greedy approach. In this case, the greedy algorithm gave the wrong results.<\/p>\n<h3>Problems solved by Greedy Method<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Problems-solved-by-Greedy-Method.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81207\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Problems-solved-by-Greedy-Method.jpg\" alt=\"Problems solved by Greedy Method\" width=\"1300\" height=\"500\" \/><\/a><\/p>\n<p>The greedy method is well versed to solve multiple types of problems. Some of them are:<\/p>\n<p>1. Fractional knapsack problem<\/p>\n<p>2. Prim\u2019s algorithm<\/p>\n<p>3. Dijkstra\u2019s algorithm<\/p>\n<p>4. Kruskal\u2019s algorithm<\/p>\n<p>5. Activity search problem<\/p>\n<p>6. Huffman coding<\/p>\n<p>7. Travelling salesperson problem<\/p>\n<p>8. Ford- Fulkerson algorithm<\/p>\n<p>9. Boruvka\u2019s algorithm<\/p>\n<p>Let us discuss all of these in detail.<\/p>\n<h4>1. Fractional Knapsack Problem<\/h4>\n<p>It is an optimization problem in which we can select fractional items rather than binary choices. The objective is to obtain a filling knapsack that maximizes the total profit earned.<\/p>\n<p><strong>Step 1:<\/strong> Calculate the ratio of value overweight for every item. If the weight is in pounds, calculate the value per pound.<\/p>\n<p><strong>Step 2:<\/strong> Sort the items depending on the ratio calculated in step 1.<\/p>\n<p><strong>Step 3:<\/strong> Take the item with the highest ratio i.e. take the maximum possible value of substance with the maximum value per pound.<\/p>\n<p><strong>Step 4:<\/strong> Suppose that the amount that we took in step 3 exhausts but we still have space. Then, we will take the further possible amount of substance with the further maximum value of weight.<br \/>\ni.e. we will take the next highest ratio.<\/p>\n<p><b>Algorithm:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">fractional_knapsack (array w, array v, int C)\n{\n    for i= 1 to size (v) do\n        for i= 1 to size (v);\n    sort_descending (vpp);\n     i := 1;\n     while (C&gt;0) do{\n         amt = min (C, w [i]);\n         sol [i] = amt;\n         C= C - amt;\n          i := i+1;\n     }\n     return sol;\n}\n<\/pre>\n<h4>2. Prims algorithm<\/h4>\n<p>It is a greedy algorithm to obtain a minimum spanning tree. Its time complexity is of the order O(n2).<\/p>\n<p>This algorithm builds the tree edge by edge, where it chooses the edge based on some optimization criterion. One of the criteria is to choose an edge in such a way that the increase in the sum of costs of edges is minimum.<\/p>\n<p>The algorithm takes the input in the form of a graph. It then chooses the subset of edges of the graph in such a way that<\/p>\n<p>a. The graph forms a tree including every vertex<br \/>\nb. The graph has the minimum sum of weight among all the subtrees.<\/p>\n<p><strong>Algorithm :<\/strong><\/p>\n<p>The steps are as follows:<\/p>\n<p>1: Initialize a vertex for the minimum spanning tree.<\/p>\n<p>2: Search for all the edges that connect the tree to new vertices.<\/p>\n<p>3: Find the minimum of all those selected edges.<\/p>\n<p>4: Add this value to the tree.<\/p>\n<p>5: We will perform the above steps recursively to reach the minimum spanning tree.<\/p>\n<p><strong>Stages in Prim\u2019s algorithm:<\/strong><\/p>\n<p>Let us look through an example to understand the stages in Prim\u2019s algorithm:<\/p>\n<p>Consider the following graph.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image04.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81212\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image04.jpg\" alt=\"Prim's Algorithm\" width=\"400\" height=\"400\" \/><\/a><\/p>\n<p>1. Select any random vertex, say \u2018A\u2019 here.<\/p>\n<p>2. Select the edge with the minimum weight from this node and add it to the existing node.<\/p>\n<p>3. Choose the nearest vertex that we can include.<\/p>\n<p>4. Repeat these above steps recursively to obtain based on the minimum spanning tree.<\/p>\n<p>The various stages of spanning tree will be:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image05.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81213\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image05.jpg\" alt=\"Stages of Spanning Tree\" width=\"1100\" height=\"800\" \/><\/a><\/p>\n<p>The final obtained spanning tree is:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image06.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81214\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image06.jpg\" alt=\"Spanning Tree\" width=\"420\" height=\"420\" \/><\/a><\/p>\n<h4>3. Dijkstra\u2019s algorithm<\/h4>\n<p>In a graph, there can exist multiple paths between a pair of vertices.\u00a0But, if we wish o find the shortest possible path between any two vertices, we make use of Dijkstra\u2019s algorithm.\u00a0It may or may not include all the vertices.<\/p>\n<p>It is somewhat similar to Prim\u2019s algorithm and is used to find the shortest path just like Pri\u2019s algorithm.<\/p>\n<p>While executing, it maintains two different sets. One set contains those vertices which we have included in the shortest path. The other set contains the remaining vertices, which we haven\u2019t included yet.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<p>1. Consider the following graph:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image07.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81215\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image07.jpg\" alt=\"Dijkstra\u2019s algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>2. Select any vertex randomly. Consider it as the starting vertex.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image08.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81216\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image08.jpg\" alt=\"Dijkstra\u2019s algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>Consider the remaining vertices to be at an infinite distance from the starting vertex.<\/p>\n<p>3. From the starting vertex, traverse to every immediate vertex. As we reach the particular vertex, we update its path in our graph.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image09.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81217\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image09.jpg\" alt=\"Traversing in Dijkstra\u2019s algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>If the adjacent path of a particular vertex is greater than the current path, do not update the values.<\/p>\n<p>4. Repeat step 3.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image10.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81218\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image10.jpg\" alt=\"Dijkstra\u2019s algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>Do not change or update the path of those nodes which we have already visited once.<\/p>\n<p>5. Check if there is still any unvisited node in the graph or not. If an unvisited node still exists, select the path with the shortest possible distance to reach that node.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image11.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81219\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image11.jpg\" alt=\"Dijkstra\u2019s algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>This is how we calculate the shortest path using Dijkstra\u2019s algorithm.<\/p>\n<h4>4. Kruskal algorithm<\/h4>\n<p>It is another possible interpretation to find out the minimum spanning tree in a graph. A minimum spanning tree always has one edge less than the number of edges in the graph.<br \/>\nThis algorithm also ensures that there are no loops created on adding edges to the tree.<\/p>\n<p><strong>Algorithm:<\/strong><\/p>\n<p>1. Sort all the edges of the graph in non-descending order of their weights.<\/p>\n<p>2. Take the smallest edge.<\/p>\n<p>3. Check whether it is forming a cycle or not with the spanning-tree formed so far.<\/p>\n<p>4. If a cycle is found, discard this particular edge leading to the cycle. If there is no cycle, include the edge in the spanning tree.<\/p>\n<p>5. Repeat the above steps until we have included all the vertices.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<p>Consider the following graph:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image12.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81220\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image12.jpg\" alt=\"Kruskal algorithm Example\" width=\"400\" height=\"400\" \/><\/a><\/p>\n<p>a. We need to find the minimum spanning tree for this graph using Kruskal\u2019s algorithm.<\/p>\n<p>b. Select the edge having minimum weight. If multiple edges are having minimum weight, choose any one of them randomly.<\/p>\n<p>c. Select the next shortest edge with the next minimum weight. Add it to the spanning tree.<\/p>\n<p>d. Select the subsequent edges, in the same manner, depending on their weights.<\/p>\n<p>e. Make sure that none of the added edges forms a cycle.<\/p>\n<p>f. Repeat the above steps until we get our desired spanning tree.<\/p>\n<p>Thus, the various stages of Kruskal\u2019s algorithm are as follows:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image13.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81221\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image13.jpg\" alt=\"Stages of Kruskal algorithm\" width=\"1100\" height=\"800\" \/><\/a><\/p>\n<h4>5. Activity search problem<\/h4>\n<p>It is an optimization problem. This algorithm selects non-conflicting activities which we can perform in the given time frame. This problem schedules activities in the given intervals in such a way that maximum activities can be performed in the given time constraint.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<p>1. Let there be \u2018n\u2019 activities ranging from 1 to n in a given set i.e. let S = {1,2,3,4,5,&#8230;&#8230;&#8230;,n-1, n}.<\/p>\n<p>2. Only one activity can use a resource at a time i.e. the resources are non-sharable.<\/p>\n<p>3. Let the start time for these \u2018n\u2019 activities be s1, s2, s3, s4,&#8230;&#8230;sn.<\/p>\n<p>4. Let the finish time of these activities be f1, f2, f3,f4,&#8230;&#8230;&#8230;.fn.<\/p>\n<p>5. Consider two random activities \u2018i\u2019 and \u2018j\u2019. Then, let the interval of activity \u2018i\u2019 be [si, fi) and the interval of activity \u2018j\u2019 be (sj, fj).<\/p>\n<p>In this case, activities \u2018i\u2019 and \u2018j\u2019 will be compatible only when their intervals i.e. [si, fi) and (sj, fj) respectively, do not overlap.<\/p>\n<h4>Activity search problem <strong>Algorithm:<\/strong><\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Algorithm Activity_Selector(s, f)\n{\n    n := len[s];\n    A := {1};\n    j := 1;\n    for i := 2 to n do{\n        if (si \u2265 fi) then\n            A := A U {i};\n        j := i;\n    }\n    return A;\n}\n<\/pre>\n<p><span style=\"font-weight: 400\">Let us consider an example to understand the activity\/task scheduling problem.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Suppose there are 7 tasks named a,b,c,d,e,f,g.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The following table gives the starting and finishing time for each task:<\/span><\/p>\n<table style=\"height: 433px\" width=\"613\">\n<tbody>\n<tr>\n<td><b>TASK<\/b><\/td>\n<td><b>START TIME<\/b><\/td>\n<td><b>FINISH TIME<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">a<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">2<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">b<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">c<\/span><\/td>\n<td><span style=\"font-weight: 400\">4<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">d<\/span><\/td>\n<td><span style=\"font-weight: 400\">9<\/span><\/td>\n<td><span style=\"font-weight: 400\">11<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">e<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<td><span style=\"font-weight: 400\">10<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">f<\/span><\/td>\n<td><span style=\"font-weight: 400\">1<\/span><\/td>\n<td><span style=\"font-weight: 400\">5<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">g<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<td><span style=\"font-weight: 400\">8<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Our objective is to assign these tasks to the computer in such a way that no two tasks overlap. We can make use of multiple machines. But since this is a greedy approach, we need to minimize the number of machines that we use for performing these tasks.<\/p>\n<p>Initially, we will consider that the number of machines used = number of tasks i.e. we are assigning each task to an individual machine. In this case, the number of machines = 7(M1, M2, M3, M4, M5, M6, M7).<\/p>\n<p>We will try to optimize the problem by minimizing the number of machines and at the same time, prevent overlapping. Thus, the final optimized schedule will be:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image14.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81222\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image14.jpg\" alt=\"Activity search problem\" width=\"750\" height=\"350\" \/><\/a><\/p>\n<p>Here, we can clearly see that we were able to schedule all the activities in three turns or by using three machines i.e. M1, M2 and M3.<\/p>\n<h4>6. Huffman Coding<\/h4>\n<p>Huffman coding algorithm is used to compress data without the loss of any information from it. Each code is a binary string used for transmitting corresponding messages.\u00a0A decode tree decodes at the receiving end.<\/p>\n<p>Huffman coding assigns codes in such a way that the most frequent character gets the lowest code and vice versa. For this purpose, the algorithm maintains a table depicting the occurrence\/frequency of characters.<\/p>\n<table style=\"height: 125px\" width=\"402\">\n<tbody>\n<tr>\n<td><b>Character<\/b><span style=\"font-weight: 400\">\u00a0<\/span><\/td>\n<td><span style=\"font-weight: 400\">a<\/span><\/td>\n<td><span style=\"font-weight: 400\">e<\/span><\/td>\n<td><span style=\"font-weight: 400\">i<\/span><\/td>\n<td><span style=\"font-weight: 400\">o<\/span><\/td>\n<td><span style=\"font-weight: 400\">u<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>frequency<\/b><\/td>\n<td><span style=\"font-weight: 400\">45<\/span><\/td>\n<td><span style=\"font-weight: 400\">13<\/span><\/td>\n<td><span style=\"font-weight: 400\">12<\/span><\/td>\n<td><span style=\"font-weight: 400\">14<\/span><\/td>\n<td><span style=\"font-weight: 400\">16<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><span style=\"font-weight: 400\">This table shows that \u2018a\u2019 occurs 45 times in the string, \u2018e\u2019 occurs 13 times and so on.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here, a occurs maximum number of times, therefore it will have the lowest code.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Total bits required:= ( 45*1+13*4+12*4+14*3+16*3 )*1000 = 210,000 bits.<\/span><\/p>\n<table>\n<tbody>\n<tr>\n<td><span style=\"font-weight: 400\">Character\u00a0<\/span><\/td>\n<td><span style=\"font-weight: 400\">code<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">a<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">e<\/span><\/td>\n<td><span style=\"font-weight: 400\">101<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">i<\/span><\/td>\n<td><span style=\"font-weight: 400\">110<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">o<\/span><\/td>\n<td><span style=\"font-weight: 400\">100<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">u<\/span><\/td>\n<td><span style=\"font-weight: 400\">111<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Fixed length Code:<\/strong><\/p>\n<p>It assigns 3 bits to each character. Thus, for the whole file, we will need 3 x 106 bits.<\/p>\n<p><strong>Variable-length code:<\/strong><\/p>\n<p>It assigns long bits to less frequent characters and short bits to more frequent characters.<\/p>\n<p><strong>Huffman Coding Algorithm:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Huffman_codes(C)\n{\n    n=|C|;\n    Q := C;\n    for i=1 to n-1 do{\n        z= allocate-Node ();\n        x = left[z]=Extract-Min(Q);\n        y= right[z] =Extract-Min(Q);\n        arr [z]=arr[x]+arr[y];\n        Insert (Q, z);\n    }\n    return Extract-Min (Q);\n}\n<\/pre>\n<h4>7. Travelling Salesman Problem<\/h4>\n<p>This problem states that there is a salesman who needs to visit a given set of cities starting from a particular city. We need to design the algorithm in such a way that the salesman cannot visit a city more than once. Also, he needs to return to the starting point after visiting all the cities.<\/p>\n<p>We need to find the minimum possible path for the salesman to travel across all the cities. We make use of an adjacency matrix to depict the connected cities.<\/p>\n<p>Consider a set of N cities- C1, C2, C3\u2026&#8230;Cn. let the cost of travelling be Tij for travelling between Ci and Cj.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image15.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81223\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image15.jpg\" alt=\"Travelling Salesman Problem\" width=\"1200\" height=\"900\" \/><\/a><\/p>\n<p>The adjacency matrix for the above path will be as follows:<\/p>\n<table style=\"height: 550px\" width=\"670\">\n<tbody>\n<tr>\n<td><span style=\"font-weight: 400\">\u00a0\u00a0<\/span><\/td>\n<td><span style=\"font-weight: 400\">C1<\/span><\/td>\n<td><span style=\"font-weight: 400\">C2<\/span><\/td>\n<td><span style=\"font-weight: 400\">C3<\/span><\/td>\n<td><span style=\"font-weight: 400\">C4<\/span><\/td>\n<td><span style=\"font-weight: 400\">C5<\/span><\/td>\n<td><span style=\"font-weight: 400\">C6<\/span><\/td>\n<td><span style=\"font-weight: 400\">C7<\/span><\/td>\n<td><span style=\"font-weight: 400\">C8<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C1<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">5<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C2<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">4<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C3<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">4<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C4<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">1<\/span><\/td>\n<td><span style=\"font-weight: 400\">8<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C5<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">1<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">2<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C6<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<td><span style=\"font-weight: 400\">8<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">9<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C7<\/span><\/td>\n<td><span style=\"font-weight: 400\">3<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">C8<\/span><\/td>\n<td><span style=\"font-weight: 400\">5<\/span><\/td>\n<td><span style=\"font-weight: 400\">7<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<td><span style=\"font-weight: 400\">2<\/span><\/td>\n<td><span style=\"font-weight: 400\">9<\/span><\/td>\n<td><span style=\"font-weight: 400\">6<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><span style=\"font-weight: 400\">Thus, the shortest path is: C1\u2192C5\u2192C4\u2192C2\u2192 C3 \u2192C6\u2192C8\u2192C7\u2192C1<\/span><\/p>\n<p><span style=\"font-weight: 400\">Cost = 3 + 1 + 6 + 4 + 6 + 9 + 6 + 3 = 38.<\/span><\/p>\n<h4>8. Ford \u2013 Fulkerson algorithm<\/h4>\n<p>This algorithm calculates the maximum possible flow in a graph. A flow network comprises vertices and edges with a source(S) and a sink (T).<\/p>\n<p>All the vertices can both send and receive data equally. However, the source can only send the data whereas the sink can only receive the data.<\/p>\n<p><strong>Augmenting path:<\/strong> It is a path available in the flow network.<\/p>\n<p><strong>Residual graph:<\/strong> It is a flow network with the additional possible flow.<\/p>\n<p>Residual capacity: It determines the capacity of an edge after removing the flow from maximum capacity.<\/p>\n<p><strong>Algorithm:<\/strong><\/p>\n<p>1. Initialize all the flow in the edges to zero.<\/p>\n<p>2. If there exists an augmenting path between the source(S) and sink(T), add that path to the flow.<\/p>\n<p>3. Update residual graph alongside.<\/p>\n<p><strong>Example:<\/strong><br \/>\nConsider the following system of pipes with a fixed maximum capacity.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image16.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81224\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image16.jpg\" alt=\"Ford \u2013 Fulkerson algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>1. Select any path from S to T i.e. source to sink.<br \/>\nLet us select S\u2192A\u2192T.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image17.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81225\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image17.jpg\" alt=\"Ford \u2013 Fulkerson algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>2. Update all the capacities in the graph.<br \/>\nHere, the minimum capacity is off the edge A \u2192 T(2).<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image18.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81226\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image18.jpg\" alt=\"Ford \u2013 Fulkerson algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>3. Select another path S\u2192B\u2192A\u2192C\u2192T.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image19.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81227\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image19.jpg\" alt=\"Ford \u2013 Fulkerson algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>4. Update the capacities again.<br \/>\nNow the minimum capacity is from the edge S \u2192 B(3).<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image20.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81228\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image20.jpg\" alt=\"Ford \u2013 Fulkerson algorithm\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p>On adding all the flows i.e. 2+3, we get 5. Thus, this is the maximum flow possible.<\/p>\n<h4>9. Boruvka\u2019s algorithm<\/h4>\n<p>This algorithm is used to find the minimum spanning tree or forest in a graph.\u00a0Using this algorithm, we can calculate the minimum spanning tree for a connected, weighted and non-directed graph.<\/p>\n<p>For example, suppose we wish to calculate the minimum spanning tree for the following graph using Boruvka\u2019s algorithm.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image21.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81229\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image21.jpg\" alt=\"Boruvka\u2019s algorithm\" width=\"700\" height=\"350\" \/><\/a><\/p>\n<p>Step 1: The very first step is to initialize all the vertices as separate components as shown:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image22.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81230\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image22.jpg\" alt=\"Boruvka\u2019s algorithm\" width=\"700\" height=\"350\" \/><\/a><\/p>\n<p>Step 2: Start from any vertex. Find the closest and the least weighted vertex and connect to the initial\/starting vertex.<\/p>\n<p>For example, let\u2019s start from \u2018A\u2019. the closest components from \u2018A\u2019 are \u2018B\u2019 and \u2018C\u2019. Out of B and C, B has lesser weight. Therefore, we will draw an edge between A and B.<\/p>\n<p>Step 3: Continue this process until all the nodes are traversed. The graph will look something like this.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image23.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81231\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image23.jpg\" alt=\"Boruvka\u2019s algorithm\" width=\"700\" height=\"350\" \/><\/a><\/p>\n<p>Continue the process until we get the MST. Thus, the final MST is:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image24.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81232\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Greedy-method-normal-image24.jpg\" alt=\"Boruvka\u2019s algorithm\" width=\"700\" height=\"350\" \/><\/a><\/p>\n<h3>Greedy method vs Dynamic programming<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>Greedy<\/b><\/td>\n<td><b>Dynamic<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">In greedy, we select the current best and then try to solve the problem arising after it.<\/span><\/td>\n<td><span style=\"font-weight: 400\">In dynamic, we select at each step, but it depends on the solution of subproblems.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">This is more efficient at finding an optimal solution.<\/span><\/td>\n<td><span style=\"font-weight: 400\">This is less efficient at finding an optimal solution.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">It may or may not get an optimal solution, but it will always get a feasible solution.<\/span><\/td>\n<td><span style=\"font-weight: 400\">This is less efficient but it guarantees the optimal solution<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Example: fractional knapsack<\/span><\/td>\n<td><span style=\"font-weight: 400\">Example: 0\/1 knapsack<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Conclusion<\/h3>\n<p><span style=\"font-weight: 400\">The greedy method is one of the most important techniques for designing algorithms. This is primarily because it has many real-world applications and it applies to a wide variety of problems.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">This article has given a fair idea of how to approach a problem using the greedy method. It also tells how and where we can use the greedy method and all the possible use cases of the algorithm.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>We encounter various types of computational problems each of which requires a different technique for solving. A problem that requires a maximum or minimum result is the optimization problem. There are broadly 3 ways&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81206,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3555],"tags":[3625,3626,3627,3628,3629,3630],"class_list":["post-81061","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structure","tag-greedy-algorithm","tag-greedy-algorithm-advantages","tag-greedy-algorithm-history","tag-greedy-algorithm-properties","tag-greedy-algorithm-with-applications","tag-greedy-algorithm-working"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Greedy Algorithm with Applications - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about greedy algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Greedy Algorithm with Applications - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about greedy algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-23T03:30:10+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Greedy-ALgorithms.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"24 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Greedy Algorithm with Applications - TechVidvan","description":"Learn about greedy algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/","og_locale":"en_US","og_type":"article","og_title":"Greedy Algorithm with Applications - TechVidvan","og_description":"Learn about greedy algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage.","og_url":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-06-23T03:30:10+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Greedy-ALgorithms.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"24 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Greedy Algorithm with Applications","datePublished":"2021-06-23T03:30:10+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/"},"wordCount":3913,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Greedy-ALgorithms.jpg","keywords":["Greedy Algorithm","Greedy Algorithm advantages","Greedy Algorithm History","Greedy Algorithm Properties","Greedy Algorithm with Applications","Greedy Algorithm working"],"articleSection":["Data Structure Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/","url":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/","name":"Greedy Algorithm with Applications - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Greedy-ALgorithms.jpg","datePublished":"2021-06-23T03:30:10+00:00","description":"Learn about greedy algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Greedy-ALgorithms.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Greedy-ALgorithms.jpg","width":1200,"height":628,"caption":"Greedy Algorithms"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/greedy-algorithm\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Greedy Algorithm with Applications"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81061","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81061"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81061\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/81206"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81061"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81061"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81061"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}