MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / merge_sort

Function merge_sort

divide_and_conquer/mergesort.py:60–106  ·  view source on GitHub ↗

Returns a list of sorted array elements using merge sort. >>> from random import shuffle >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> shuffle(array) >>> merge_sort(array) [-2

(array: list)

Source from the content-addressed store, hash-verified

58
59
60def merge_sort(array: list) -> list:
61 """Returns a list of sorted array elements using merge sort.
62
63 >>> from random import shuffle
64 >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
65 >>> shuffle(array)
66 >>> merge_sort(array)
67 [-200, -10, -2, 3, 11, 99, 100, 100000]
68
69 >>> shuffle(array)
70 >>> merge_sort(array)
71 [-200, -10, -2, 3, 11, 99, 100, 100000]
72
73 >>> array = [-200]
74 >>> merge_sort(array)
75 [-200]
76
77 >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]
78 >>> shuffle(array)
79 >>> sorted(array) == merge_sort(array)
80 True
81
82 >>> array = [-2]
83 >>> merge_sort(array)
84 [-2]
85
86 >>> array = []
87 >>> merge_sort(array)
88 []
89
90 >>> array = [10000000, 1, -1111111111, 101111111112, 9000002]
91 >>> sorted(array) == merge_sort(array)
92 True
93 """
94 if len(array) <= 1:
95 return array
96 # the actual formula to calculate the middle element = left + (right - left) // 2
97 # this avoids integer overflow in case of large N
98 middle = 0 + (len(array) - 0) // 2
99
100 # Split the array into halves till the array length becomes equal to One
101 # merge the arrays of single length returned by mergeSort function and
102 # pass them into the merge arrays function which merges the array
103 left_half = array[:middle]
104 right_half = array[middle:]
105
106 return merge(merge_sort(left_half), merge_sort(right_half))
107
108
109if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

mergeFunction · 0.70

Tested by

no test coverage detected