Skip to content

Instantly share code, notes, and snippets.

@mlshv
Created April 29, 2017 07:12
Show Gist options
  • Select an option

  • Save mlshv/616735cf3ca09138a62437a1aaa6c8c2 to your computer and use it in GitHub Desktop.

Select an option

Save mlshv/616735cf3ca09138a62437a1aaa6c8c2 to your computer and use it in GitHub Desktop.
Recursive Merge Sort (Python)
def divide(a):
return a[:len(a)//2], a[len(a)//2:]
def merge(a, b):
result = []
while(True):
if len(a) == 0:
result += b
break
elif len(b) == 0:
result += a
break
if a[0] < b[0]:
result.append(a.pop(0))
else:
result.append(b.pop(0))
return result
def merge_sort_recursive(a):
a, b = divide(a)
if len(a) == 0 or len(b) == 0:
return merge(a, b)
a = merge_sort_recursive(a)
b = merge_sort_recursive(b)
return merge(a, b)
if __name__ == '__main__':
import random
a = random.sample(range(30), 11)
print(merge_sort_recursive(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment