Difference Between Greedy Knapsack and 0/1 Knapsack Algorithms
Last Updated :
23 Jul, 2025
The 0/1 Knapsack algorithm is a dynamic programming approach where items are either completely included or not at all. It considers all combinations to find the maximum total value. On the other hand, the Greedy Knapsack algorithm, also known as the Fractional Knapsack, allows for items to be broken into fractions, selecting items with the highest value-to-weight ratio first. However, this approach may not provide the optimal solution for the 0/1 Knapsack problem.
The greedy knapsack is an algorithm for making decisions that have to make a locally optimal choice at each stage in the hope that this will eventually lead to the best overall decision. In other words, it chooses items that have high value-to-weight ratios by iteratively selecting them based on increasing cost-benefit ratio whereby those items whose price can be paid less per unit utility derived from them are always preferred over others. Therefore, at any point in time, it just picks the item with a higher value/weight ratio without considering future consequences.
Steps of the Greedy Knapsack Algorithm:
- Find out value-to-weight ratios for all items: This implies dividing the worth of every item by its weight.
- Rearrange items according to their value-to-weight ratios: Order them according to who has first got the highest ratio.
- Go through the sorted list: Starting from the highest rationed item add items to the knapsack until there’s no more leftover space or no more other considerations about components.
Example:
Suppose we have a knapsack with a capacity of 50 units and the following items with their respective values and weights:
Item 1: Value = 60, Weight = 10
Item 2: Value = 100, Weight = 20
Item 3: Value = 120, Weight = 30
Using the greedy approach, we sort the items based on their value-to-weight ratio:
Item 3 (120/30 = 4)
Item 2 (100/20 = 5)
Item 1 (60/10 = 6)
Now, starting with the highest ratio, we add items to the knapsack until its capacity is reached:
Knapsack: Item 3 (Value: 120, Weight: 30) + Item 2 (Value: 100, Weight: 20)
Total Value: 220
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Structure for an item which stores weight and
// corresponding value of Item
struct Item {
int value, weight;
// Constructor
Item(int value, int weight)
: value(value)
, weight(weight)
{
}
};
// Comparison function to sort Item according to
// value/weight ratio
bool cmp(struct Item a, struct Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}
// Main greedy function to solve problem
double fractionalKnapsack(int W, struct Item arr[], int n)
{
// sorting Item on basis of ratio
sort(arr, arr + n, cmp);
// Uncomment to see new order of Items with their
// ratio
/*
for (int i = 0; i < n; i++) {
cout << arr[i].value << " " << arr[i].weight << " :
" << ((double)arr[i].value / arr[i].weight) << endl;
}
*/
int curWeight = 0; // Current weight in knapsack
double finalvalue = 0.0; // Result (value in Knapsack)
// Looping through all Items
for (int i = 0; i < n; i++) {
// If adding Item won't overflow, add it completely
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalvalue += arr[i].value;
}
// If we can't add current Item, add fractional part
// of it
else {
int remain = W - curWeight;
finalvalue
+= arr[i].value
* ((double)remain / arr[i].weight);
break;
}
}
// Returning final value
return finalvalue;
}
// Driver code
int main()
{
int W = 50; // Weight of knapsack
Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum value we can obtain = "
<< fractionalKnapsack(W, arr, n);
return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;
// Structure for an item which stores weight and
// corresponding value of Item
class Item {
int value, weight;
// Constructor
public Item(int value, int weight)
{
this.value = value;
this.weight = weight;
}
}
public class Main {
// Comparison function to sort Item according to
// value/weight ratio
static class ItemComparator
implements Comparator<Item> {
public int compare(Item a, Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
if (r1 < r2)
return 1;
else if (r1 > r2)
return -1;
return 0;
}
}
// Main greedy function to solve problem
static double fractionalKnapsack(int W, Item arr[],
int n)
{
// sorting Item on basis of ratio
Arrays.sort(arr, new ItemComparator());
int curWeight = 0; // Current weight in knapsack
double finalValue
= 0.0; // Result (value in Knapsack)
// Looping through all Items
for (int i = 0; i < n; i++) {
// If adding Item won't overflow, add it
// completely
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalValue += arr[i].value;
}
else {
// If we can't add current Item, add
// fractional part of it
int remain = W - curWeight;
finalValue
+= arr[i].value
* ((double)remain / arr[i].weight);
break;
}
}
// Returning final value
return finalValue;
}
// Driver code
public static void main(String[] args)
{
int W = 50; // Weight of knapsack
Item arr[] = { new Item(60, 10), new Item(100, 20),
new Item(120, 30) };
int n = arr.length;
System.out.println("Maximum value we can obtain = "
+ fractionalKnapsack(W, arr, n));
}
}
Python
from typing import List
# Class representing an item with value and weight
class Item:
def __init__(self, value: int, weight: int):
self.value = value
self.weight = weight
# Function to compare items based on value/weight ratio
def item_comparator(a: Item, b: Item) -> int:
r1 = a.value / a.weight
r2 = b.value / b.weight
if r1 < r2:
return 1
elif r1 > r2:
return -1
return 0
# Main greedy function to solve the problem
def fractional_knapsack(W: int, arr: List[Item]) -> float:
# Sorting items based on ratio
arr.sort(key=lambda x: item_comparator(x, x))
cur_weight = 0 # Current weight in knapsack
final_value = 0.0 # Result (value in Knapsack)
# Looping through all items
for item in arr:
# If adding the item won't overflow, add it completely
if cur_weight + item.weight <= W:
cur_weight += item.weight
final_value += item.value
else:
# If we can't add the current item, add fractional part of it
remain = W - cur_weight
final_value += item.value * (remain / item.weight)
break
# Returning the final value
return final_value
# Driver code
if __name__ == "__main__":
W = 50 # Weight of knapsack
arr = [Item(60, 10), Item(100, 20), Item(120, 30)]
print("Maximum value we can obtain =", fractional_knapsack(W, arr))
JavaScript
// Structure for an item which stores weight and
// corresponding value of Item
class Item {
constructor(value, weight) {
this.value = value;
this.weight = weight;
}
}
// Comparison function to sort Item according to
// value/weight ratio
function cmp(a, b) {
let r1 = a.value / a.weight;
let r2 = b.value / b.weight;
return r1 > r2;
}
// Main greedy function to solve problem
function fractionalKnapsack(W, arr) {
// sorting Item on basis of ratio
arr.sort(cmp);
let curWeight = 0; // Current weight in knapsack
let finalvalue = 0.0; // Result (value in Knapsack)
// Looping through all Items
for (let i = 0; i < arr.length; i++) {
// If adding Item won't overflow, add it completely
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalvalue += arr[i].value;
}
// If we can't add current Item, add fractional part of it
else {
let remain = W - curWeight;
finalvalue += arr[i].value * (remain / arr[i].weight);
break;
}
}
// Returning final value
return finalvalue;
}
// Driver code
let W = 50; // Weight of knapsack
let arr = [new Item(60, 10), new Item(100, 20), new Item(120, 30)];
console.log("Maximum value we can obtain = ", fractionalKnapsack(W, arr));
OutputMaximum value we can obtain = 240
An alternative approach of the dynamic programming is taken by the 0/1 Knapsack Algorithm unlike that which is greedy. This is why it was named “0/1” since it completely takes or leaves each item which is a binary decision. The algorithm guarantees an overall optimal but can become very expensive for large number of problem sizes.
Steps of the 0/1 Knapsack Algorithm:
- Create a table: A table will be initialized to store maximum value that can be obtained with different weights and items.
- Fill the table iteratively: For every item and every possible weight, determine whether including the item would increase its value without exceeding the weight limit.
- Use the table to determine the optimal solution: Follow through backward in order to find items that have been included in optimal solution.
Example:
Suppose we have a knapsack with a capacity of 5 units and the following items with their respective values and weights:
Item 1: Value = 6, Weight = 1
Item 2: Value = 10, Weight = 2
Item 3: Value = 12, Weight = 3
We construct a dynamic programming table to find the optimal solution:
0/1 KnapsackFinally, we find that the optimal solution is to include Item 2 and Item 3:
Knapsack: Item 2 (Value: 10, Weight: 2) + Item 3 (Value: 12, Weight: 3)
Total Value: 22
Difference between Greedy Knapsack and 0/1 Knapsack Algorithm:
Criteria
| Greedy Knapsack
| 0/1 Knapsack
|
---|
Approach
| Greedy strategy, locally optimal choices
| Dynamic programming, considers all options
|
---|
Decision Making
| Based on value-to-weight ratio
| Considers all possible combinations
|
---|
Complexity
| O(n log n) - Sorting
| O(nW) - Where n is the number of items, W is the capacity
|
---|
Optimal Solution
| Not always optimal
| Always optimal
|
---|
Item Inclusion
| May include fractions of items
| Items are either fully included or excluded
|
---|
Memory Usage
| Requires less memory
| Requires more memory due to DP table
|
---|
Algorithm Type
| Greedy
| Dynamic Programming
|
---|
Sorting
| Requires sorting based on certain criteria
| No sorting required
|
---|
Speed
| Faster due to greedy selection
| Slower due to exhaustive search
|
---|
Use Cases
| Quick approximation, large datasets
| Small datasets, guaranteed optimality
|
---|
Conclusion
To sum up, both greedy knapsack and 0/1 knapsack algorithms have different trade offs between optimality and efficiency. Fast solutions may come from greedy knapsack but such solutions are not optimal in some cases whereas 0/1 knap sack guarantee that at the cost of high computational complexity. This understanding will form a basis upon which to select an appropriate algorithm for a given knapsack problem.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem