Knapsack in Greedy

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

KNAPSACK IN GREEDY

• Name : Athar Sheikh


• En no. : 170410107112
• Class : CE-2(Batch C)
• Subject : Analysis and Design of Algorithm
GREEDY METHOD

• Characteristics of greedy algorithm:


• make a sequence of choices
• each choice is the one that seems best so far,
only
• depends on what's been done so far
• choice produces a smaller problem to be
solved
PHASES OF GREEDY ALGORITHM

A greedy algorithm works in phases.

 At each phase:

 takes the best solution right now, without regard for

future consequences
 choosing a local optimum at each step, and end up
at a
global optimum solution.
KNAPSACK PROBLEM

There are two version of knapsack problem

1. 0-1 knapsack problem:


 Items are indivisible. (either take an item or not)
 can be solved with dynamic programming.

2. Fractional knapsack problem:


 Items are divisible. (can take any fraction of an item)
 It can be solved in greedy method
FRACTIONAL KNAPSACK PROBLEM

• A thief robbing a store finds n items.

• ith item: worth vi value of item and wi weight of item


• W, wi, vi are integers.

• He can carry at most W pounds.

• He can take fractions of items.


THE OPTIMAL KNAPSACK ALGORITHM

This algorithm is for time complexity O(n lgn))


(1) Sort the n objects from large to small based on the ratios vi/wi . We
assume the
arrays w[1..n] and v[1..n] store the respective weights and
values after sorting.

(2)initialize array x[1..n] to zeros.


(3)weight = 0; i = 1
(4)while (i  n and weight < W) do
(I) else x[i] = (W – weight) / w[i]
(II) if weight + w[i]  W then x[i] = 1
(III) weight = weight + x[i] * w[i]
(IV) i++
KNAPSACK PROBLEM

•There seem to be 3 obvious greedy strategies:

1. Max Value(V): Sort the objects from the highest value to the lowest,
then pick them in that order.

2. Min Weight(W) :Sort the objects from the lowest weight to the
highest, then pick them in that order.

3. Value/Weight(V/W) :Sort the objects based on the value to weight


ratios, then select from the highest to the lowest.
• Example: Given n = 5 objects and a knapsack capacity W = 100
as in Table

• The three solutions are given in Table


YOU
NK
TH A

You might also like