Repository where I mostly put random python scripts.
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.

27 lines
569 B

  1. def merge_sort(a):
  2. if len(a) < 2:
  3. return a
  4. l = a[0:len(a)//2]
  5. r = a[len(a)//2:]
  6. return merge(merge_sort(l), merge_sort(r))
  7. def merge(a, b):
  8. out = []
  9. i = 0
  10. j = 0
  11. while i < len(a) or j < len(b):
  12. if i >= len(a):
  13. out.append(b[j])
  14. j += 1
  15. elif j >= len(b):
  16. out.append(a[i])
  17. i += 1
  18. else:
  19. if a[i] <= b[j]:
  20. out.append(a[i])
  21. i += 1
  22. else:
  23. out.append(b[j])
  24. j += 1
  25. return out