Every star now has an ID number. Nova keeps the IDs in a list, sorted from smallest to biggest.
Rocket needs star 27. He starts at the front out of habit. Then he stops himself. "Wait. This list is sorted!"
Raven smiles. "What do you notice about the number in the middle?"
"It is 15," Rocket says. "27 is bigger, so it must be on the right side."
Nova glows. "Great discovery! Here is a hint. Keep track of where the possible part starts and ends."
We keep two spot numbers. The variable low is the first spot still possible. The variable high is the last one.
The middle spot is mid = (low + high) // 2. The // sign divides and drops any remainder, so 7 // 2 is 3.
print(7 // 2) print(8 // 2) print((4 + 7) // 2)
Output: 3 4 5
| Spot | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| ID | 3 | 8 | 12 | 15 | 21 | 27 | 30 | 36 |
print(9 // 2) print(10 // 3) print((0 + 9) // 2) print((5 + 9) // 2)
| Spot | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| ID | 2 | 5 | 9 | 14 | 20 | 23 | 31 |
| Statement | True or false? |
|---|---|
| The first mid for this list is spot 3. | ? |
| 8 // 2 is 4. | ? |
| 7 // 2 is 3.5. | ? |
| low and high mark the part of the list still possible. | ? |
Nice halving! You searched a sorted list the way a computer does. Tomorrow we read the binary search code.