You are on page 1of 1

ABHINAV ARORA 09

ASSIGNMENT (DAA)
PSEUDO CODE for knapsack problem:
Greedy-Fractional-Knapsack (w[1..n], p[1..n], W)
for i = 1 to n
do x[i] = 0
weight = 0
for i = 1 to n
if weight + w[i] ≤ W then
x[i] = 1
weight = weight + w[i]
else
x[i] = (W - weight) / w[i]
weight = W
break
return x

EXAMPLE-
(p1, p2, p3) = (25,24,15)
(w1, w2, w3) = (18,15,10)

Strategy 1= Maximize objective function


(Put the object with greatest profit in knapsack)
Σpixi = 25*1+ (24*2)/15+0= 28.5
Σwixi = 18*1+(15*2)/15+0= 20
Solution is still not optimal.

Strategy 2= Maximize capacity


(Choose objects according to least weight)
Σpixi = 0+(24*2)/3+15*1=31
Σwixi = 0+(15*2)/3+10*1=20
Solution is still not optimal.

Strategy 3= Balancing profit and capacity


(Find the object to include by maximum profit per unit of capacity)
Σpixi = 0+24*1+(15*1)/2=31.5
Σwixi = 0+15*1+(10*1)/2=20
Solution is optimal.

Achieves a balance between the rate at which profit increases with the rate at
which the capacity is used.

Analysis= If we do not consider the time considered for sorting the inputs then all of the three
greedy strategies complexity will be 0(n).

You might also like