Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

The middle of a queue

Seven people stand in a queue. Who's in the middle? The one with three people in front and three behind: the fourth person. Counting from 0, that's box 3.

Notice where 3 comes from: 7 halved is 3.5, rounded down to 3. That works for any odd length. Halve the length, round down, and you land on the box with the same number of values on each side.

Middle box: the length halved, rounded down.
Find the middle of 7 boxes
4
0
8
1
15
2
16
3
23
4
42
5
7
6
i

The length is 7, so indices run from 0 to 6.

Move 1 of 3

Why rounding down is the right way

With 9 boxes, halving gives 4.5. Round down to 4: boxes 0 to 3 sit on the left and boxes 5 to 8 on the right, four on each side. Rounding up to 5 would leave five before it and only three after.

Counting from 0 is what makes rounding down land in exactly the right place.

Divide with rounding down: a plain / gives a fraction in Python.
In code
middle = len(nums) // 2
return nums[middle]