Rocket wants the computer to merge sorted lists for the catalog. He uses two fingers on the screen to track the fronts.
"My fingers are the spot numbers," he says. "One for each list."
Raven watches. "What do you notice about when a finger moves?"
"Only the finger on the card I took moves forward," Rocket says.
Nova hums. "Here is a hint. Use i for one finger and j for the other."
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:]
print(merge([2, 5, 8], [3, 4, 9])) Output: [2, 3, 4, 5, 8, 9]
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])
____
return result + left[i:] + right[j:]
print(merge([2, 5, 8], [3, 4, 9])) 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:]
print(merge([1, 3, 5], [2, 4]))
print(merge([], [7, 8]))
print(merge([6], [6])) | Statement | True or false? |
|---|---|
| merge returns a sorted list when both inputs are sorted. | ? |
| Both i and j move forward on every pass. | ? |
| left[i:] is empty when i equals len(left). | ? |
| merge works when one list is empty. | ? |
Excellent! merge is the heart of merge sort. Tomorrow we learn how to get sorted piles to merge in the first place.