1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-10-29 22:17:23 +01:00

feat(solutions): add sorting-algorithms/python/merge-sort

This commit is contained in:
Divlo 2021-06-29 20:35:07 +02:00
parent d1c9a7ef3e
commit 0c441c2e9d
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
2 changed files with 53 additions and 0 deletions

View File

@ -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)) |

View File

@ -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)