Here’s a clear, no-frills way to code Merge Sort in Python, plus some notes on how/why it works.
1. The Big Idea
Merge Sort is a classic divide-and-conquer algorithm:
- Divide: Recursively split the list into halves until each sub-list has 0 – 1 items (which are “already sorted”).
- Conquer / Merge: Re-assemble those tiny lists back into a single sorted list by repeatedly “merging” two sorted halves.
Because merging two sorted lists is linear (O(n)), and we do it at each level of splitting (log₂n levels), the whole algorithm runs in O(n log n) time and requires O(n) extra space for the temporary lists.
2. A Straightforward Implementation
def merge_sort(arr):
# Base case: a list of 0 or 1 items is already sorted
if len(arr) <= 1:
return arr
# 1) Divide
mid = len(arr) // 2
left_half = merge_sort(arr[:mid]) # recursively sort left half
right_half = merge_sort(arr[mid:]) # recursively sort right half
# 2) Conquer / Merge
return merge(left_half, right_half)
def merge(left, right):
"""
Merge two *sorted* lists into a single sorted list.
"""
merged = []
i = j = 0
# Compare heads of both lists and append smaller one
while i < len(left) and j < len(right):
if left[i] < right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
# One of the lists may have leftover items
merged.extend(left[i:])
merged.extend(right[j:])
return merged
3. Quick Demo
data = [38, 27, 43, 3, 9, 82, 10]
sorted_data = merge_sort(data)
print(sorted_data) # ➜ [3, 9, 10, 27, 38, 43, 82]
4. Why Use return Instead of In-place?
The version above uses functional style (returns a new list) because it’s simple to reason about and bug-free for beginners. If you need in-place sorting to save memory, you can:
- Allocate a single auxiliary array and pass it down (common in C/Java).
- Or mutate the original list during merging (Pythonic variant below).
5. In-Place (well… “less extra allocation”) Variant
def merge_sort_inplace(arr, start=0, end=None):
if end is None:
end = len(arr)
# Base case
if end - start <= 1:
return
mid = (start + end) // 2
merge_sort_inplace(arr, start, mid)
merge_sort_inplace(arr, mid, end)
# Merge two adjacent sorted slices [start:mid] and [mid:end]
merged = []
i, j = start, mid
while i < mid and j < end:
if arr[i] <= arr[j]:
merged.append(arr[i]); i += 1
else:
merged.append(arr[j]); j += 1
merged.extend(arr[i:mid])
merged.extend(arr[j:end])
# Copy back to original array
arr[start:end] = merged
Call with:
arr = [5, 8, 6, 1, 10]
merge_sort_inplace(arr)
print(arr) # ➜ [1, 5, 6, 8, 10]
This still needs O(n) extra storage per merge level (the merged list), but avoids repeated slice allocation.
6. Complexity Recap
| Aspect | Cost |
|---|
| Time (best/avg/worst) | O(n log n) |
| Space (extra) | O(n) |
| Stable? | Yes (order of equal elements preserved) |
| Adaptive? | No (doesn’t speed up on nearly-sorted data) |
7. When to Choose Merge Sort
✔ Great for linked lists (merge is O(1) extra space).
✔ Performs well on large datasets that don’t fit in cache (sequential access).
✔ Stable sort (important for multi-key sorts).
✘ Uses extra memory for arrays.
✘ Quicksort or Timsort (Python’s built-in .sort()) are often faster for in-memory data because of lower constants and better cache/memory behavior.
Happy coding! 🎉