|
| 1 | +import unittest |
| 2 | +from typing import List |
| 3 | +import random |
| 4 | + |
| 5 | + |
| 6 | +def merge_sort(inp: List[int]): |
| 7 | + """ |
| 8 | + split the input (n elements) into 2 sub-arrays with n/2 elements |
| 9 | + sort these 2 sub-arrays recursively by merge_sort |
| 10 | + merge 2 sorted sub-arrays to produce the result |
| 11 | + :param inp: |
| 12 | + :return: |
| 13 | + """ |
| 14 | + if len(inp) <= 1: |
| 15 | + return inp |
| 16 | + # split |
| 17 | + mid_index = len(inp) // 2 |
| 18 | + # sort sub-lists |
| 19 | + left = inp[:mid_index] |
| 20 | + right = inp[mid_index:] |
| 21 | + print(f'left: {left}, right: {right}') |
| 22 | + left = merge_sort(inp[:mid_index]) |
| 23 | + right = merge_sort(inp[mid_index:]) |
| 24 | + |
| 25 | + # merge sorted sub-lists |
| 26 | + left_index = 0 |
| 27 | + right_index = 0 |
| 28 | + i = 0 |
| 29 | + while i < len(inp): |
| 30 | + if left[left_index] >= right[right_index]: |
| 31 | + inp[i] = right[right_index] |
| 32 | + right_index += 1 |
| 33 | + else: |
| 34 | + inp[i] = left[left_index] |
| 35 | + left_index += 1 |
| 36 | + i += 1 |
| 37 | + if left_index == len(left): |
| 38 | + inp[i:] = right[right_index:] |
| 39 | + break |
| 40 | + if right_index == len(right): |
| 41 | + inp[i:] = left[left_index:] |
| 42 | + break |
| 43 | + return inp |
| 44 | + |
| 45 | + |
| 46 | +class MergeSortTest(unittest.TestCase): |
| 47 | + |
| 48 | + def test_case1(self): |
| 49 | + input = [1, 2, 3, 4, 5] |
| 50 | + self.assertEqual(input, merge_sort(input)) |
| 51 | + |
| 52 | + def test_case2(self): |
| 53 | + input = [5, 4, 3, 2, 1] |
| 54 | + self.assertEqual([1, 2, 3, 4, 5], merge_sort(input)) |
| 55 | + |
| 56 | + def test_cases(self): |
| 57 | + random.seed(42) |
| 58 | + for i in range(0, 50): |
| 59 | + inp = random.sample(range(0, 10), 10) |
| 60 | + print(f'input: {inp}') |
| 61 | + self.assertEqual([0,1,2,3,4,5,6,7,8,9], merge_sort(inp)) |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == '__main__': |
| 65 | + unittest.main() |
0 commit comments