You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
programming-basics-2022/03/merge/imlementation.py

47 lines
1021 B

from collections import deque
from typing import List, Deque
def merge(
els1: List[int],
els2: List[int],
) -> List[int]:
"""
Merges two sorted lists into one, keeps order.
>>> merge([1, 2, 3], [3, 4, 5])
[1, 2, 3, 3, 4, 5]
"""
result = []
i, j = 0, 0
while i < len(els1) and j < len(els2):
if els1[i] < els2[j]:
result.append(els1[i])
i += 1
else:
result.append(els2[j])
j += 1
result.extend(els1[i:])
result.extend(els2[j:])
return result
def mergesort(elements: List[int]) -> List[int]:
"""
Sorts a given list.
"""
# -> if len(elements) == 0:
# if not elements:
if len(elements) <= 1:
return elements
buffer: Deque[List[int]] = deque()
for el in elements:
buffer.append([el])
while len(buffer) > 1:
h1: List[int] = buffer.popleft()
h2: List[int] = buffer.popleft()
buffer.append(merge(h1, h2))
return buffer.pop()