From 0c441c2e9d1c55328c3f85a3ae2bab004f9a8d30 Mon Sep 17 00:00:00 2001 From: Divlo Date: Tue, 29 Jun 2021 20:35:07 +0200 Subject: [PATCH] feat(solutions): add `sorting-algorithms/python/merge-sort` --- .../solutions/python/merge-sort/README.md | 7 +++ .../solutions/python/merge-sort/solution.py | 46 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 challenges/sorting-algorithms/solutions/python/merge-sort/README.md create mode 100644 challenges/sorting-algorithms/solutions/python/merge-sort/solution.py diff --git a/challenges/sorting-algorithms/solutions/python/merge-sort/README.md b/challenges/sorting-algorithms/solutions/python/merge-sort/README.md new file mode 100644 index 0000000..821e2d7 --- /dev/null +++ b/challenges/sorting-algorithms/solutions/python/merge-sort/README.md @@ -0,0 +1,7 @@ +# sorting-algorithms/python/merge-sort + +Created by [@Divlo](https://github.com/Divlo) on 29 June 2021. + +| Algorithm | Best Case | Average Case | Worst Case | +| ----------------------------------------------------------- | ----------- | ------------ | ----------- | +| [Merge sort](https://wikipedia.org/wiki/Merge_sort) | O(n log(n)) | O(n log(n)) | O(n log(n)) | diff --git a/challenges/sorting-algorithms/solutions/python/merge-sort/solution.py b/challenges/sorting-algorithms/solutions/python/merge-sort/solution.py new file mode 100644 index 0000000..467e506 --- /dev/null +++ b/challenges/sorting-algorithms/solutions/python/merge-sort/solution.py @@ -0,0 +1,46 @@ +from typing import List, Any +import sys + + +def divide_list(values: List[Any]) -> List[Any]: + middle = len(values) // 2 + left = values[middle:] + right = values[:middle] + return [left, right] + + +def merge(numbers_1: List[int], numbers_2: List[int]) -> List[int]: + length_numbers_1 = len(numbers_1) + length_numbers_2 = len(numbers_2) + index_numbers_1 = 0 + index_numbers_2 = 0 + result: List[int] = [] + while index_numbers_1 < length_numbers_1 and index_numbers_2 < length_numbers_2: + if numbers_1[index_numbers_1] < numbers_2[index_numbers_2]: + result.append(numbers_1[index_numbers_1]) + index_numbers_1 += 1 + else: + result.append(numbers_2[index_numbers_2]) + index_numbers_2 += 1 + for index_numbers_1 in range(index_numbers_1, length_numbers_1, 1): + result.append(numbers_1[index_numbers_1]) + for index_numbers_2 in range(index_numbers_2, length_numbers_2, 1): + result.append(numbers_2[index_numbers_2]) + return result + + +def merge_sort(numbers: List[int]) -> List[int]: + if len(numbers) <= 1: + return numbers + left, right = divide_list(numbers) + left, right = merge_sort(left), merge_sort(right) + return merge(left, right) + + +numbers: List[int] = [] +for value in sys.stdin: + numbers.append(int(value.rstrip('\n'))) + +sorted_numbers = merge_sort(numbers) +for number in sorted_numbers: + print(number)