Mission Control asks which sort the fleet should use for the big catalog.
Rocket and Raven run both sorts on the same lists. Nova keeps a tally of every comparison.
"For 8 cards, selection sort is not so bad," Rocket says. Then the lists get longer.
Raven reads the tallies. "What do you notice as the lists double?"
Nova shows the numbers in big glowing digits. "Here is a hint. Look at how fast each column grows."
We ran both sorts on the same mixed-up lists, with a tally of every comparison.
| Items | Selection sort | Merge sort |
|---|---|---|
| 8 | 28 | 17 |
| 16 | 120 | 47 |
| 32 | 496 | 124 |
| 64 | 2,016 | 307 |
Selection sort compares each card with almost every other card. Doubling the list makes about four times the work.
Merge sort splits in halves, so it has few levels. Doubling the list makes only two to three times the work.
| Statement | True or false? |
|---|---|
| Merge sort uses recursion. | ? |
| Selection sort uses less work for long lists. | ? |
| Both sorts give the same sorted list. | ? |
def selection_comparisons(n):
return n * (n - 1) // 2
for n in [8, 16, 32, 64, 128]:
print(n, selection_comparisons(n)) | Statement | True or false? |
|---|---|
| selection_comparisons(16) returns 120. | ? |
| Doubling the list doubles selection sort's work. | ? |
| Merge sort made 307 comparisons for 64 items in the table. | ? |
| For 8 items, the two sorts are fairly close. | ? |
Week 9 complete! You built a sort that splits, sorts and merges, and you measured why it wins. Next week we explore trees.