Binary search on the answer
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Binary search is usually met as a way to find an item in a sorted list. Here it searches something else: the possible answers to a question. Six boxes of 4, 8, 3, 5, 6, 2 kg must ship in order within 2 days, and we want the smallest truck capacity that works. A yes/no check loads the trucks for one capacity; because the answers run no, no, ..., yes, yes, each check throws away half of the 21 candidates, and 5 checks find 15. The Software lesson "Searching: linear and binary" introduces binary search on a sorted list; this lesson reuses the same halving loop.
Ship boxes in two days
Six boxes weigh 4, 8, 3, 5, 6, 2 kg. They must ship in this order, over at most 2 days. Each day one truck takes boxes until the next would pass its capacity. What is the smallest capacity that works?
ws = [4, 8, 3, 5, 6, 2] (kg, in shipping order) d = 2 (days allowed) one truckload per day; boxes stay in order question: the smallest capacity cap with every box shipped in d days
اقرأ الدرس خطوة بخطوة
Ship boxes in two days
Six boxes weigh 4, 8, 3, 5, 6, 2 kg. They must ship in this order, over at most 2 days. Each day one truck takes boxes until the next would pass its capacity. What is the smallest capacity that works?
ws = [4, 8, 3, 5, 6, 2] (kg, in shipping order) d = 2 (days allowed) one truckload per day; boxes stay in order question: the smallest capacity cap with every box shipped in d daysThe answer has a range
We do not search a list here: we search the answers. The capacity is at least 8, the heaviest box, and at most 28, all boxes in one day. So lo = 8, hi = 28: 21 whole-number candidates.
lo = max(ws) = 8 (a smaller truck cannot lift the 8 kg box) hi = sum(ws) = 28 (one day, everything: always fits) candidates: 8, 9, ..., 28 → 21 valuesTest the middle: 18
Binary search tests the middle candidate: mid = (8 + 28) // 2 = 18. Python's // divides and rounds down. The rings over the day plinths rise to 18 kg: that is the truck capacity we will try.
mid = (lo + hi) // 2 = (8 + 28) // 2 = 18 // is floor division: 36 / 2 = 18 exactly here capacity under test: 18 kgOne check: load the trucks
fits() loads boxes in order and starts a new day when the next box would pass the ring. Day 1: 4, 8, 3 (15 kg). Day 2: 5, 6, 2 (13 kg). 2 days: 18 fits.
def fits(ws, cap, d): days, load = 1, 0 for w in ws: if load + w > cap: days, load = days + 1, 0 load += w return days <= d day 1: 4 + 8 + 3 = 15 day 2: 5 + 6 + 2 = 13 2 days ≤ 2: fits(ws, 18, 2) is TrueYes, then always yes
A bigger truck never needs more days. So once 18 fits, every capacity above it fits too: the answers run no, no, ..., yes, yes. We want the first yes, so hi = 18 and 19 to 28 are dropped.
monotone: fits(c) is True ⇒ fits(c + 1) is True fits(18) is True, so the first yes is at 18 or below hi = mid = 18; window 8 .. 1813 is too small
mid = (8 + 18) // 2 = 13. Day 1 takes 4 and 8 (12); day 2 takes 3 and 5 (8); 6 and 2 spill into day 3. Too many days, so every smaller capacity fails too: lo = 14.
mid = (8 + 18) // 2 = 13 day 1: 4 + 8 = 12 day 2: 3 + 5 = 8 day 3: 6 + 2 = 8 3 days > 2: fits(ws, 13, 2) is False lo = mid + 1 = 14 window now 14 .. 1816 fits
mid = (14 + 18) // 2 = 16. Same split as for 18: 15 kg, then 13 kg. Two days, so it fits: hi = 16. The window is now 14 to 16, three candidates.
mid = (14 + 18) // 2 = 16 day 1: 4 + 8 + 3 = 15 day 2: 5 + 6 + 2 = 13 2 days ≤ 2: fits(ws, 16, 2) is True hi = mid = 16 window now 14 .. 1615 fits exactly
mid = (14 + 16) // 2 = 15. Day 1 holds 15 kg, exactly full; day 2 holds 13. Still two days: hi = 15.
mid = (14 + 16) // 2 = 15 day 1: 4 + 8 + 3 = 15 day 2: 5 + 6 + 2 = 13 2 days ≤ 2: fits(ws, 15, 2) is True hi = mid = 15 window now 14 .. 1514 fails: answer 15
mid = 14. Day 1: 12 kg. Day 2: 3, 5, 6 (14). The 2 needs day 3, so lo = 15. Now lo = hi = 15 and the loop stops: the smallest capacity is 15 kg.
mid = (14 + 15) // 2 = 14 day 1: 4 + 8 = 12 day 2: 3 + 5 + 6 = 14 day 3: 2 = 2 3 days > 2: fits(ws, 14, 2) is False lo = mid + 1 = 15 window now 15 .. 15 lo == hi: return lo = 15Why it is fast
5 checks found 15 among 21 candidates; counting up from 8 takes 8. Each check halves the window and reads all n boxes once, so the cost is O(n log R) for R candidates. It works because the answers never flip back to no.
checks: 18 yes, 13 no, 16 yes, 15 yes, 14 no binary search: 5 checks (⌈log2 21⌉ = 5) linear scan 8, 9, ...: 8 checks one check = one pass over n boxes: O(n) total: O(n log R), R = sum(ws) - max(ws) + 1
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01With boxes 4, 8, 3, 5, 6, 2 kg shipped in order, what does fits(ws, 13, 2) return, and why?
Day 1 takes 4 and 8 (12); adding 3 would make 15, so day 2 starts with 3 and 5 (8); adding 6 would make 14, so 6 and 2 need day 3. Three days is more than 2.
02Why is the search range for the capacity max(ws) to sum(ws)?
Below max(ws) the heaviest box never fits, so those capacities are always no. At sum(ws) one day carries everything, so that capacity is always yes. The answer lies between them.
03fits(18) is True. What does the search do next, and why is that safe?
The test is monotone: a bigger truck never needs more days. So once 18 fits, 19 to 28 fit too and cannot be the smallest. hi = mid keeps 18 in case it is the answer.
04About how many checks does binary search on the answer need for 21 candidates, and for about a billion?
Each check at least halves the window: ⌈log2 21⌉ = 5, and log2 of a billion is just under 30. Each check still costs one pass over the n boxes.
05Which property must the yes/no test have for binary search on the answer to be correct?
Binary search finds the boundary between a run of no and a run of yes. If the answers could flip back to no, discarding half the range could throw away the true answer. The candidates do not need to be stored: they are just the numbers lo to hi.
المسرد
- Answer space
- All the values the answer could take. Here, the whole-number capacities from 8 to 28.
- Feasibility check
- A yes/no test for one candidate answer. Here fits(ws, cap, d): can the boxes ship in d days with this capacity?
- Monotone test
- A test that never flips back: if it says yes for x, it says yes for every larger x. The answers run no, ..., no, yes, ..., yes.
- lo and hi
- The ends of the window of candidates still in play. The loop stops when they meet.
- mid
- The candidate tested next: (lo + hi) // 2, the middle of the window, rounded down.
- Floor division (//)
- Python's integer division that rounds down: 29 // 2 is 14.
- Greedy
- Making the best-looking local choice at each step. fits() fills each day as far as it can before starting the next.
الملاحظات والمصادر
- The trick needs a monotone test: if fits(c) is True then fits(c + 1) is True. Here that holds because a bigger truck can carry every load a smaller one could, so the greedy never needs more days. Without that property binary search can skip past the answer.
- fits() is greedy: it fills each day as far as it can before starting the next. For boxes that must stay in order this is optimal: if any plan ships in d days, the greedy one does too, because filling day 1 as far as possible never leaves more boxes for later.
- The code is real Python 3. min_cap([4, 8, 3, 5, 6, 2], 2) returns 15. The same search with the standard library: bisect_left(range(lo, hi + 1), True, key=lambda c: fits(ws, c, d)) + lo (key= needs Python 3.10 or later).
- Each check at least halves the window of candidates, so 21 candidates need at most ⌈log2 21⌉ = 5 checks. With capacities up to a billion it would be about 30.
- Sedgewick and Wayne, Algorithms 4th ed., §3.1 Elementary Symbol Tables (binary search, Proposition B)
- Sedgewick and Wayne, Algorithms 4th ed., §1.1 Programming Model (BinarySearch)
- MIT 6.006 Introduction to Algorithms (Fall 2011), Lecture 1: Algorithmic Thinking, Peak Finding
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022)
- Python Library Reference: bisect, Array bisection algorithm
- Python Language Reference: Binary arithmetic operations (floor division)
اختبار يتاح بعد الخطوة الأخيرة.