Now turn merge into a full sort. Merge sort splits the list in half, sorts each half recursively, then merges the two sorted halves back together.
Write merge_sort(arr) that returns a NEW sorted list. Do not mutate arr.
Requirements:
Merge sort runs in O(n log n) time and is stable, which we will exploit in Step 5.
def merge(a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result.extend(a[i:])
result.extend(b[j:])
return result
def merge_sort(arr):
"""Return a new sorted list using recursive divide-and-merge."""
# TODO: base case len<=1; split at mid; recurse; combine with merge().
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Now turn merge into a full sort. Merge sort splits the list in half, sorts each half recursively, then merges the two sorted halves back together.
Write merge_sort(arr) that returns a NEW sorted list. Do not mutate arr.
Requirements:
Merge sort runs in O(n log n) time and is stable, which we will exploit in Step 5.
Press Run Tests or ββ© to check your solution.