merge_sort.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # merge sort
  2. # http://interactivepython.org/courselib/static/pythonds/SortSearch/TheMergeSort.html
  3. import pytest
  4. def test_merge_sort():
  5. input1 = [31, 23, 43, 56, 9]
  6. input2 = []
  7. assert merge_sort(input1) == [9, 23, 31, 43, 56]
  8. assert merge_sort(input2) == []
  9. def merge_sort(input):
  10. if len(input) > 1:
  11. mid = len(input)//2
  12. left = input[:mid]
  13. right = input[mid:]
  14. merge_sort(left)
  15. merge_sort(right)
  16. # in-place merge, the merge always starts from the left as
  17. # merge_sort(left) is called first
  18. i,j,k = 0,0,0
  19. # sync compare
  20. while i < len(left) and j < len(right):
  21. if left[i] < right[j]:
  22. input[k] = left[i]
  23. i += 1
  24. else:
  25. input[k] = right[j]
  26. j += 1
  27. k += 1
  28. # the larger ones
  29. while i < len(left):
  30. input[k] = left[i]
  31. i += 1
  32. k += 1
  33. while j < len(right):
  34. input[k] = right[j]
  35. j += 1
  36. k += 1
  37. return input