CodeBlanks Logo Icon CodeBlanks

Challenge 1

Sort an array with merge sort and print it.

Challenge 1: Merge sort

In this challenge you will sort an array with merge sort and print it. Combine prior skills.

Array: [5, 2, 8, 1, 9]. Sorted output: [1, 2, 5, 8, 9].

Merge sort gives O(n log n) by dividing, sorting recursively and merging.

Practice Merge sort

Write merge_sort(arr). Sort the array with merge sort and return it. Print [1, 2, 5, 8, 9] with print(merge_sort([5, 2, 8, 1, 9])).

Starter code

solution.py
def merge_sort(arr):
    # Sort with merge sort

Sample solution

solution.py
def merge_sort(arr):
    # Sort with merge sort
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    return merge(left, right)
def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i]); i += 1
        else:
            result.append(right[j]); j += 1
    result.extend(left[i:]); result.extend(right[j:])
    return result
print(merge_sort([5, 2, 8, 1, 9]))

Expected output

[1, 2, 5, 8, 9]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is merge sort's complexity?

  • O(n^2)
  • O(n log n) Correct answer
  • O(log n)
  • O(n)

Explanation: O(n log n).

2 Mid index

Question
mid = len(arr) ____ 2
Answer
mid = len(arr) // 2

Explanation: // is right.

3 Challenge 1: match the terms

Term Meaning
merge sort Divide merge
O(n log n) Fast
stable Keeps order
divide Split

All lessons in Intermediate