Decision Mathematics 1 (Paper 3D or 4D), topic 1 (Algorithms and graph theory), spec point 1.2
Bin packing
Items of different sizes go into bins of equal capacity. The aim is to use as few bins as possible.
Lower bound: , rounded up.
- First-fit: take items in the given order; put each into the first bin with room.
- First-fit decreasing: sort into descending order first, then use first-fit. This usually does better.
- Full bins: look for combinations that fill bins exactly, then use first-fit for the rest.
Worked example 1
Items 8, 7, 14, 9, 6, 9, 5, 15, 6, 7, 8 go into bins of capacity 20. The total is 94, so the lower bound is bins.
First-fit uses 6 bins: [8, 7, 5], [14, 6], [9, 9], [15], [6, 7], [8].
First-fit decreasing (15, 14, 9, 9, 8, 8, 7, 7, 6, 6, 5) uses 5 bins: [15, 5], [14, 6], [9, 9], [8, 8], [7, 7, 6]. This equals the lower bound, so it is optimal.
Bubble sort
Compare the first two items and swap them if they are in the wrong order. Then compare the second and third, and so on to the end of the list: that is one pass. After each pass the largest remaining item is in its final place, so the next pass can stop one item earlier. Stop when a pass makes no swaps.
Worked example 2
Sort 6, 2, 9, 4, 1, 7 into ascending order.
| After pass | List | Swaps |
|---|---|---|
| 1 | 2, 6, 4, 1, 7, 9 | 4 |
| 2 | 2, 4, 1, 6, 7, 9 | 2 |
| 3 | 2, 1, 4, 6, 7, 9 | 1 |
| 4 | 1, 2, 4, 6, 7, 9 | 1 |
| 5 | 1, 2, 4, 6, 7, 9 | 0 |
Quick sort
Choose the middle item as the pivot. In a list of items that is item if is odd and item if is even. Write the items smaller than the pivot to its left and the rest to its right, keeping their order. Repeat on each sub-list until every item has been a pivot or is on its own.
Worked example 3
Sort 23, 14, 38, 9, 31, 17, 26, 12. There are 8 items, so the pivot is the 5th, 31.
- Pivot 31: 23, 14, 9, 17, 26, 12 | 31 | 38
- Left list (6 items), pivot is the 4th, 17: 14, 9, 12 | 17 | 23, 26
- 14, 9, 12: pivot 9, giving 9 | 14, 12. Then 14, 12: pivot 12, giving 12 | 14.
- 23, 26: pivot 26, giving 23 | 26.
Sorted: 9, 12, 14, 17, 23, 26, 31, 38.
Common mistake: rounding the bin lower bound down, or forgetting that the lower bound may not be achievable. Also, in quick sort, items must keep their original order within each sub-list.
Exam tip: show the state of every bin or the list after every pass. If asked for descending order, sort that way from the start rather than reversing at the end.
Check yourself
Items total 73 and bins hold 15. Find the lower bound.
.
Which item is the pivot in a list of 10?
The 6th.
When does bubble sort stop?
After a pass with no swaps.