Dividing whole numbers hides a tie
transcript
A sort key can hide a bug. Take two print jobs. Job one: length 1, weight 2. Job two: length 1, weight 3. Sort by length over weight. A division rounds. Watch what happens.
One divided by two is zero. One divided by three is also zero. The jobs look equal. The list order stays. Cross-multiplying gives three against two. They differ.
In list order, job one goes first. The cost is two, plus six. That is eight. Heavier first costs three, plus four. That is seven. Rounding cost us one.
Do not divide. Multiply instead. Compare a length times b weight. Against b length times a weight. Use 64-bit numbers when products grow large. Lengths and weights can be large.
Never divide to compare ratios. Cross-multiply, and the tie is gone. The heavier job runs first, as it should. One extra unit of cost is a real bug. Full breakdown in the lecture.