Skip to content

Instantly share code, notes, and snippets.

@xiabingquan
Created January 24, 2025 16:11
Show Gist options
  • Save xiabingquan/4de81c20ce7e3b567c1e40e53db368b7 to your computer and use it in GitHub Desktop.
Save xiabingquan/4de81c20ce7e3b567c1e40e53db368b7 to your computer and use it in GitHub Desktop.
A minimal example of merge sort
from __future__ import annotations
import random
from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) == 1 or len(arr) == 0:
return arr
mid = len(arr) // 2
left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
new = [-1 for _ in range(len(arr))]
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
new[i + j] = left[i]
i += 1
else:
new[i + j] = right[j]
j += 1
while i < len(left):
new[i + j] = left[i]
i += 1
while j < len(right):
new[i + j] = right[j]
j += 1
return new
def test_merge_sort() -> bool:
for _ in range(random.randint(1, 10)):
arr = [random.randint(0, 10) for _ in range(random.randint(10, 20))]
if not all(x == y for x, y in zip(sorted(arr), merge_sort(arr))):
return False
return True
if __name__ == "__main__":
print(f"test result = {test_merge_sort()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment