Merge Sort
See it animated in Zerethon Tools ↗Split in half, sort each half, merge the sorted halves — O(n log n), stable.
This is an older version. The current version is 1.2.0.
Implementations
Sign in to open in IDE
Sign in with your Zerethon account to create your own copy of this sample.
Files
# Merge Sort
Zerethon Official Sample `merge-sort`, version 1.0.0, Python 3.12.
- `merge_sort.py` — the algorithm, as shown in Zerethon Tools
- `main.py` — entry file: a short demonstration
- `test_merge_sort.py` — checks; set it as the entry file to run them
This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/merge-sort-visualizer
from merge_sort import merge_sort
numbers = [38, 27, 43, 3, 9, 82, 10, 27]
print("Before:", numbers)
result = merge_sort(list(numbers))
print("After: ", result)
print("Same as sorted():", result == sorted(numbers))
"""Merge Sort (Zerethon Official Sample: merge-sort 1.0.0)."""
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
# Checks for merge_sort. To run them, set this file as the entry file
# (the ▶ button next to it in Files) and press Run.
from merge_sort import merge_sort
def numbers(seed, count):
"""Deterministic pseudo-random integers in [-50, 49]."""
out = []
for _ in range(count):
seed = (seed * 1103515245 + 12345) % 2**31
out.append(seed % 100 - 50)
return out
cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]]
cases += [numbers(seed, size) for seed, size in ((1, 10), (2, 50), (3, 200))]
for case in cases:
got = merge_sort(list(case))
assert got == sorted(case), f"merge_sort({case[:6]}...) = {got[:6]}..."
print(f"All {len(cases)} checks passed.")
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Merge Sort Visualizer.