#include <stdio.h>
#include <stdlib.h>
// Structure to store item value and weight
typedef struct {
int value;
int weight;
double ratio;
} Item;
// Comparator to sort items by value/weight ratio descending
int cmp(const void *a, const void *b) {
Item *item1 = (Item *)a;
Item *item2 = (Item *)b;
if (item2->ratio > item1->ratio) return 1;
else if (item2->ratio < item1->ratio) return -1;
else return 0;
}
// Function to solve fractional knapsack
double fractionalKnapsack(Item items[], int n, int capacity) {
// Calculate ratio for each item
for (int i = 0; i < n; i++) {
items[i].ratio = (double)items[i].value / items[i].weight;
}
// Sort items by ratio descending
qsort(items, n, sizeof(Item), cmp);
double totalValue = 0.0;
int remaining = capacity;
for (int i = 0; i < n; i++) {
if (items[i].weight <= remaining) {
// Take whole item
totalValue += items[i].value;
remaining -= items[i].weight;
} else {
// Take fraction of item
totalValue += items[i].ratio * remaining;
break; // Knapsack full
}
}
return totalValue;
}
int main() {
Item items[] = {{60, 10, 0}, {100, 20, 0}, {120, 30, 0}};
int n = sizeof(items) / sizeof(items[0]);
int capacity = 50;
double maxValue = fractionalKnapsack(items, n, capacity);
printf("Maximum value in knapsack = %.2f\n", maxValue);
return 0;
}
items[i].ratio = (double)items[i].value / items[i].weight;
Calculate value per weight ratio for sorting priority
qsort(items, n, sizeof(Item), cmp);
Sort items by descending ratio to pick best value first
if (items[i].weight <= remaining) {
Check if whole item fits in remaining capacity
totalValue += items[i].value;
Add full item value to total
remaining -= items[i].weight;
Reduce remaining capacity by item weight
totalValue += items[i].ratio * remaining;
Add fractional value for partial item to fill knapsack
Stop after filling knapsack with fraction
Maximum value in knapsack = 240.00