Watch fractional knapsack sort items by value per weight and fill the bag, taking a fraction of the last item. Worked example with four items, capacity 5.
About this algorithm
Fractional knapsack fills a bag with a weight limit to get the most value, when you are allowed to take part of an item. Think of gold dust, rice or fuel rather than a laptop. Because any fraction is allowed, the best plan is simple: take the items worth the most per kilogram first, and cut the last one to fit.
Use it when goods can be divided and value scales with the amount taken: loading bulk cargo, splitting a budget across ad channels with a known return per rupee, blending ingredients. If each item must be taken whole or left behind, you have the 0/1 knapsack problem, and this greedy rule can give a wrong answer; use the dynamic programming method from the knapsack page instead. Fractional knapsack is also the bound that branch-and-bound uses to prune 0/1 knapsack searches, since no whole-item plan can beat it.
For every item divide its value by its weight. That ratio is how much each unit of capacity earns if you spend it on that item.
The best earner per kilogram goes first.
Walk the sorted list. If an item weighs no more than the remaining capacity, take all of it, add its value and subtract its weight.
When an item is heavier than the space left, take just enough to fill the bag: the fraction remaining / weight, worth that fraction of its value. The bag is now full, and every later item is skipped.
The page loads item 1 (weight 2, value 10), item 2 (weight 4, value 16), item 3 (weight 6, value 12) and item 4 (weight 3, value 3), with a capacity of 5. Their ratios are 5, 4, 2 and 1, so that is already the order. Item 1 fits: take all of it, value 10, capacity left 3. Item 2 weighs 4, more than 3, so take 3/4 of it, which is worth 0.75 × 16 = 12. The bag is full at a total value of 22. Items 3 and 4 are never touched.
Now forbid fractions. The best whole-item choice is item 2 alone, worth 16. The ratio rule would take item 1, skip item 2 because it no longer fits, skip item 3, and then take item 4, for only 13. Greedy by ratio is right for the fractional problem and wrong for the whole-item one, which is why 0/1 knapsack needs a table.
Time: computing ratios and the single pass are linear, so sorting n items by ratio is the cost that dominates. Space: a sorted copy of the items with their ratios; sorting in place would bring it down to O(1) extra.