Topic 1 · Lesson 2 of 5
Bin packing and the order of an algorithm
Bin packing
Items of different sizes must be packed into bins of a fixed capacity, using as few bins as possible: lorries with a weight limit, files on storage cards, lengths cut from standard planks. Three algorithms are used:
- First-fit: take the items in the order given; put each in the first bin with enough room. Quick, but often wasteful.
- First-fit decreasing: sort the items into descending order (by bubble sort or quick sort), then apply first-fit. Usually good, but not always optimal.
- Full bins: look for combinations of items that fill a bin exactly, pack those first, then use first-fit for the rest. Often optimal, but finding the combinations is hard when there are many items.
A lower bound for the number of bins is the total size of the items divided by the bin capacity, rounded up. If a packing uses that many bins, it must be optimal. If not, the packing may or may not be optimal: the lower bound may not be achievable.
Worked example
Bin packing
Pack items of size into bins of size 20.
Show solutionHide solution
- Lower bound: total , , so at least 5 bins.
- First-fit: bin 1: 8, 7, 5; bin 2: 14, 6; bin 3: 9, 9; bin 4: 15; bin 5: 6, 7; bin 6: 8. That is 6 bins.
- First-fit decreasing on : bin 1: 15, 5; bin 2: 14, 6; bin 3: 9, 9; bin 4: 8, 8; bin 5: 7, 7, 6. That is 5 bins, which equals the lower bound, so it is optimal.
The order of an algorithm
The order of an algorithm describes how its running time grows with the size of the problem: how many items to sort, vertices in a network, and so on. If the number of operations is roughly proportional to , the algorithm has quadratic order; to , cubic order; to , linear order. Only the highest power matters: is quadratic.
- Bubble sort and first-fit have quadratic order (at most comparisons).
- Floyd's algorithm has cubic order: each of the iterations updates up to entries.
To estimate a run time, scale by the ratio of sizes raised to the order. If an algorithm of quadratic order takes 2 seconds for 500 items, then 1500 items take about seconds. These are estimates: the order describes the worst case or the general trend, and real times also depend on the data.
Practise this topic
Both are part of Premium.