Solve the fractional knapsack problem using a greedy algorithm. Select items by their value-to-weight ratio to maximize total value within a weight capacity.
The fractional knapsack problem allows items to be divided into fractional parts. The greedy strategy sorts items by value-to-weight ratio in descending order, then fills the knapsack by selecting items with highest ratio first. This greedy choice always yields the optimal solution for this variant.
Selection State
| Item | Weight | Value | Ratio | Status |
|---|
Total Value & Weight
Value: 0.0 | Weight: 0.0
Step Info
Waiting to solve...
Algorithm & Pseudocode
| Aspect | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(n) |
| Greedy Choice | Max Ratio |
Implementation
typedef struct: Defines Item structure holding weight and value as doubles for fractional calculations.
compare(): Comparator for qsort computes value/weight ratio on-the-fly for each item pair, returns 1 or -1 to sort descending by ratio. Essential for greedy selection.
qsort(): Standard library function performs sorting in O(n log n) time. Pass items array, count, size of each element, and comparator function pointer.
Main Loop: Iterates through sorted items in order of best ratio. If item fits fully, add entire value; else calculate fractional part and break (greedy fill).
Fractional Calculation: Line 19 computes (remaining_capacity / item_weight) * item_value—the maximum value achievable by partially taking an item.
Time Complexity: O(n log n) dominated by sorting; greedy iteration is O(n). Space O(n) for storing items.