38 lines
656 B
Python
38 lines
656 B
Python
|
|
||
|
def merge(a, b):
|
||
|
"""Merges two sorted lists"""
|
||
|
i, j = 0, 0
|
||
|
r = []
|
||
|
while i < len(a) and j < len(b):
|
||
|
if a[i] < b[j]:
|
||
|
r.append(a[i])
|
||
|
i += 1
|
||
|
else:
|
||
|
r.append(b[j])
|
||
|
j += 1
|
||
|
|
||
|
while i < len(a):
|
||
|
r.append(a[i])
|
||
|
i += 1
|
||
|
|
||
|
while j < len(b):
|
||
|
r.append(b[j])
|
||
|
j += 1
|
||
|
return r
|
||
|
|
||
|
|
||
|
def merge_sort(v):
|
||
|
length = len(v)
|
||
|
if length <= 1:
|
||
|
return v
|
||
|
|
||
|
half_length = length // 2
|
||
|
|
||
|
a = merge_sort(v[:half_length])
|
||
|
b = merge_sort(v[half_length:])
|
||
|
return merge(a, b)
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
print(merge_sort([42, 12, 3, 1, 5]))
|