← Back to course
Code Crew G5 / Week 09 / Wednesday
3/6
Week 09 Β· Merge sort

Wednesday

Split until single
// Split, sort, merge
⏱ about 15 min

Wednesday: Split until single

Rocket has eight jumbled ID cards. "Merging is great," he says. "But merge needs sorted piles, and my cards are a mess!"

Raven splits the cards into two piles of four, then piles of two, then single cards.

"What do you notice about a pile with just one card?" she asks.

Rocket laughs. "It is already sorted! There is nothing to put in order."

Nova sparkles. "Here is a hint. Single cards are sorted piles. What can you do with sorted piles?"

Split in halves

To split a list in half, find the middle spot with len(items) // 2. Then slice up to it, and from it.

cards = [5, 2, 7, 1, 6, 3, 8, 4]
mid = len(cards) // 2
print(cards[:mid])
print(cards[mid:])
Output:
[5, 2, 7, 1]
[6, 3, 8, 4]

cards[:mid] takes the items before spot mid. cards[mid:] takes spot mid to the end.

Split down, merge up

LevelPiles
Start5 2 7 1 6 3 8 4
Split 15 2 7 1 | 6 3 8 4
Split 25 2 | 7 1 | 6 3 | 8 4
Split 35 | 2 | 7 | 1 | 6 | 3 | 8 | 4
Merge 12 5 | 1 7 | 3 6 | 4 8
Merge 21 2 5 7 | 3 4 6 8
Merge 31 2 3 4 5 6 7 8

Eight cards split 3 times to reach single cards. Then 3 levels of merging build them back up, sorted.

For [9, 4, 6], mid is 3 // 2, which is 1. What is [9, 4, 6][1:]? Type the list.
WHY THIS EXERCISEWhen a list has an odd length, the right half gets the extra item.
THINK ABOUT SPLITTING.
  • Read the question.
  • Tap your answer.
A list has 5 items. What is mid = 5 // 2?
How many split levels does it take to get 16 cards down to single cards?
Why stop splitting at one card?

Practice lab: split five cards

cards = [9, 3, 6, 1, 8]
mid = len(cards) // 2
print(mid)
print(cards[:mid])
print(cards[mid:])
What does print(mid) show?
How many items are in cards[:mid]?
How many items are in cards[mid:]?
How many split levels to get 32 cards down to single cards?
SPLIT CHECK
  • Read the question.
  • Tap your answer.
What is [4, 7][:1]?
How many split levels for 8 cards?
With an odd number of cards, which half gets the extra card?
StatementTrue or false?
cards[:mid] and cards[mid:] together hold every card.?
A pile of one card must be sorted again.?
16 cards need 4 split levels.?
The merging goes back up the same number of levels.?
WHY THIS EXERCISESplitting down and merging up use the same number of levels.
How many split levels does it take to get 64 cards to single cards?
WHY THIS EXERCISEEach level halves the piles, and 64 halves 6 times to reach 1.

Wonderful! You saw the whole shape of merge sort. Tomorrow we write it with recursion.

← Tuesday