Program No 8
Program No 8
Aim: Write a program to implement the Knapsack Problem using a greedy solution.
Knapsack Problem: The Knapsack Problem is a combinatorial optimization problem where the
goal is to maximize the value of items placed in a knapsack without exceeding its capacity. The
greedy approach works by selecting items based on the highest value-to-weight ratio, allowing
us to maximize the total value.
Complexity:
Worst-case complexity: O(nlogn)O(n \log n)O(nlogn) (for sorting items by their value-to-
weight ratio)
Algorithm:
o If adding an item exceeds the capacity, add a fractional portion of the item to fill
the knapsack to its limit.
Process:
3. Traverse the sorted items and add them to the knapsack, considering their weight.
4. If a full item can be added, add it; otherwise, add a fraction to maximize value without
exceeding capacity.
Source Code:
#include <stdio.h>
struct Item {
int weight;
int value;
};
int currentWeight = 0;
currentWeight += items[i].weight;
totalValue += items[i].value;
} else {
break;
items[j + 1] = temp;
}
int main() {
int n, capacity;
scanf("%d", &n);
scanf("%d", &items[i].weight);
scanf("%d", &items[i].value);
scanf("%d", &capacity);
sortItemsByRatio(items, n);
knapsack(items, n, capacity);
return 0;
Output:-
Item 1 - Weight: 10
Item 1 - Value: 60
Item 2 - Weight: 20
Item 3 - Weight: 30