Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Design and Analysis of Algorithms

Greedy Algorithm
(Fractional Knapsack Problem)

Dr. D. P. Acharjya
Professor, SCOPE
1/24/2024 Dr. D. P. Acharjya 1
Greedy Approach
 A greedy algorithm builds a solution
to a problem in steps
- Each iteration adds a part of the
solution.
 A greedy algorithm always makes the
choice that looks best at the moment
- It moves from local optimal solution
to global optimal solution.

1/24/2024 Dr. D. P. Acharjya 2


 Greedy Algorithms do not always
yield optimal solution. But, for many
problems they do.
 It works well for
 0/1 Knapsack Problem
 Minimum Spanning Tree Problem
 Shortest Path Problem
 Tree Vertex Splitting Problem

1/24/2024 Dr. D. P. Acharjya 3


Algorithm (General Greedy)
1. Algorithm Greedy (A, n)
2. Solution = 
3. For i= 1 to n
4. {
5. x = Select (a)
6. If Feasible (Solution, x)
7. Solution = Solution  {x}
8. }
9. Return Solution

1/24/2024 Dr. D. P. Acharjya 4


Knapsack Problem
 Given that a knapsack of capacity m.
Suppose that there are n-objects. Assume
that the object i has a weight wi. If a
fraction xi of object i is placed into the
knapsack, the profit is xipi.
 The main objective of knapsack problem is
to obtain a filling of the knapsack that
maximizes the total profit.
 It is a bounded linear programming
problem.
1/24/2024 Dr. D. P. Acharjya 5
Mathematical Formulation

 Equation 1 is objective function


 Equation 2 is a constraint condition
 It is a fractional knapsack problem.
1/24/2024 Dr. D. P. Acharjya 6
 The set which satisfies
equations (2) and (3) is known as feasible
solution.
 The feasible solution which maximizes the
objective function (1) is known as optimal
solution.
 Since it is a profit maximization problem,
objects having more profit in respect to
weights must be considered initially.

1/24/2024 Dr. D. P. Acharjya 7


 Therefore, to achieve our objective,
we must rearrange the objects with
respect to weights and profits.

1/24/2024 Dr. D. P. Acharjya 8


Algorithm (Knapsack Problem)
1. Greedy Knapsack (m, n)
2. For i = 1 to n
3. Set x[i] = 0
4. u=m
5. For i = 1 to n
6. if (w[i] > u)
7. then break
8. else
9. x[i] = 1.0
10. u = u – w[i]
11. If (i <=n)
12. x[i] = u / w[i]
13. u = u – w[i]x[i]

1/24/2024 Dr. D. P. Acharjya 9


Numerical Illustration

 Consider the following instance of the


knapsack problem, where the number
of objects is 3, capacity of the
knapsack is 20. The profits are (p1,
p2, p3) = (25, 24, 15) and weights
are (w1,w2,w3) = (18, 15, 10).

1/24/2024 Dr. D. P. Acharjya 10


Solution to the Problem

1/24/2024 Dr. D. P. Acharjya 11


1/24/2024 Dr. D. P. Acharjya 12


1/24/2024 Dr. D. P. Acharjya 13



1/24/2024 Dr. D. P. Acharjya 14


Optimal Solution

1/24/2024 Dr. D. P. Acharjya 15

You might also like