Created
January 24, 2025 16:11
-
-
Save xiabingquan/4de81c20ce7e3b567c1e40e53db368b7 to your computer and use it in GitHub Desktop.
A minimal example of merge sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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