Skip to content

Instantly share code, notes, and snippets.

@blacktrub
Created July 12, 2020 12:17
Show Gist options
  • Select an option

  • Save blacktrub/8f269aa228659c8b80487689be2e7872 to your computer and use it in GitHub Desktop.

Select an option

Save blacktrub/8f269aa228659c8b80487689be2e7872 to your computer and use it in GitHub Desktop.
merge sort algorithm
import math
def merge(one, two):
n = max(len(one), len(two))
i, j = 0, 0
result = []
for _ in range(n * 2):
a = one[i] if len(one) > i else None
b = two[j] if len(two) > j else None
if a is not None and b is not None:
if a < b:
result.append(a)
i += 1
else:
result.append(b)
j += 1
elif a is not None:
result.append(a)
i += 1
elif b is not None:
result.append(b)
j += 1
return result
def merge_sort(arr):
if len(arr) < 2:
return arr
n2 = int(math.ceil(float(len(arr)) / 2))
c = merge_sort(arr[:n2])
d = merge_sort(arr[n2:])
return merge(c, d)
if __name__ == '__main__':
arr = [9, 4, 2, 1, 6, 0]
result = merge_sort(arr)
assert result == sorted(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment