Guest User

Untitled

a guest
Jul 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. def merge_sort(input_list: list) -> list:
  2. """Sort list using merge sort algorithm.
  3. :param input_list: list to be sorted.
  4. :type input_list: list
  5. :return: sorted list in ascending order.
  6. :rtype: list
  7. """
  8. def merge(lst:list, p: int, q: int, r: int):
  9. """Helper function for merge sort: merge lst[p:q+1] and lst[q+1:r+1].
  10. :param lst: list to be sorted.
  11. :param p: starting index of first sublist.
  12. :param q: ending index of first sublist.
  13. :param r: ending index of second sublist.
  14. """
  15. # Use copy() to avoid changing a and b when changing original list.
  16. a = lst[p:q+1].copy()
  17. lena = q + 1 - p
  18. b = lst[q+1:r+1].copy()
  19. lenb = r - q
  20. # i and j remember progress in a and b.
  21. i = 0
  22. j = 0
  23. # Fill lst[p:r+1]
  24. for k in range(p,r+1):
  25. # a is all copied, just finish rest of b.
  26. if i == lena:
  27. lst[k] = b[j]
  28. j += 1
  29. # b is all copied, just finish rest of a.
  30. elif j == lenb:
  31. lst[k] = a[i]
  32. i += 1
  33. # a and b are both not done, need to compare.
  34. elif a[i] < b[j]:
  35. lst[k] = a[i]
  36. i += 1
  37. else:
  38. lst[k] = b[j]
  39. j += 1
  40.  
  41. def inner_sort(lst: list, p: int, r:int):
  42. """Helper function for merge sort.
  43. :param lst: list to be sorted.
  44. :type lst: list
  45. :param p: starting index.
  46. :type p: int
  47. :param r: ending index (inclusive).
  48. :type r: int
  49. """
  50. # if there is only 1 element, no need to sort.
  51. if p < r:
  52. # Determine ending index of first sublist.
  53. q = (p + r)//2
  54. # Sort left sublist.
  55. inner_sort(lst, p, q)
  56. # Sort right sublist.
  57. inner_sort(lst, q+1, r)
  58. # Merge left and right sublists.
  59. merge(lst, p, q, r)
  60.  
  61. # Architecture of merge sort algorithm.
  62. length = len(input_list)
  63. if length <= 1:
  64. return input_list
  65. else:
  66. inner_sort(input_list, 0, length - 1)
  67. return input_list
Add Comment
Please, Sign In to add comment