Rocket wants to turn the split and merge table into code. "Do I need a loop for each level?" he wonders.
Raven draws a box around one half of the cards. "What do you notice about sorting this half?"
"It is the same job as sorting the whole thing, just smaller!" Rocket says.
"Like the nesting boxes," Raven says.
Nova glows. "Here is a hint. Base case, smaller step. You know this pattern."
This version prints each merge so we can watch it work. It uses the merge function from Tuesday.
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i = i + 1
else:
result.append(right[j])
j = j + 1
return result + left[i:] + right[j:]
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
print("merging", left, right)
return merge(left, right)
print(merge_sort([5, 2, 7, 1])) Output: merging [5] [2] merging [7] [1] merging [2, 5] [1, 7] [1, 2, 5, 7]
| Statement about merge_sort | True or false? |
|---|---|
| The base case is a list with 0 or 1 items. | ? |
| merge_sort calls itself twice in each call that is not a base case. | ? |
| The right half is merged before the left half is sorted. | ? |
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i = i + 1
else:
result.append(right[j])
j = j + 1
return result + left[i:] + right[j:]
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
print("merging", left, right)
return merge(left, right)
print(merge_sort([3, 1, 2])) | Statement | True or false? |
|---|---|
| merge_sort([3]) prints nothing. | ? |
| merge_sort([3, 1, 2]) prints merging [3] [1, 2] first. | ? |
| merge_sort uses merge to join the halves. | ? |
| Each half is sorted before the merge. | ? |
Fantastic! You read a recursive sort. That is real computer science. Tomorrow we race it against selection sort.