Skip to content

Commit a74be07

Browse files
authored
Create adaptive_merge_sort.py
1 parent e9e7c96 commit a74be07

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

sorts/adaptive_merge_sort.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Adaptive Merge Sort Algorithm
3+
@see https://www.tutorialspoint.com/adaptive-merging-and-sorting-in-data-structure
4+
"""
5+
6+
def adaptive_merge_sort(sequence: list) -> list:
7+
"""
8+
Sorts a list using the Adaptive Merge Sort algorithm.
9+
10+
:param sequence: list of elements to be sorted
11+
:return: sorted list
12+
13+
>>> adaptive_merge_sort([12, 11, 13, 5, 6, 7])
14+
[5, 6, 7, 11, 12, 13]
15+
16+
>>> adaptive_merge_sort([5, 4, 3, 2, 1])
17+
[1, 2, 3, 4, 5]
18+
19+
>>> adaptive_merge_sort(['zebra', 'apple', 'mango', 'banana'])
20+
['apple', 'banana', 'mango', 'zebra']
21+
"""
22+
if len(sequence) < 2:
23+
return sequence
24+
25+
aux = sequence[:]
26+
adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1)
27+
return sequence
28+
29+
30+
def adaptive_merge_sort_helper(array: list, aux: list, low: int, high: int):
31+
if high <= low:
32+
return
33+
34+
mid = (low + high) // 2
35+
36+
adaptive_merge_sort_helper(aux, array, low, mid)
37+
adaptive_merge_sort_helper(aux, array, mid + 1, high)
38+
39+
if array[mid] <= array[mid + 1]:
40+
array[low:high + 1] = aux[low:high + 1]
41+
return
42+
43+
merge(array, aux, low, mid, high)
44+
45+
46+
def merge(array: list, aux: list, low: int, mid: int, high: int):
47+
i, j = low, mid + 1
48+
49+
for k in range(low, high + 1):
50+
if i > mid:
51+
aux[k] = array[j]
52+
j += 1
53+
elif j > high:
54+
aux[k] = array[i]
55+
i += 1
56+
elif array[j] < array[i]:
57+
aux[k] = array[j]
58+
j += 1
59+
else:
60+
aux[k] = array[i]
61+
i += 1

0 commit comments

Comments
 (0)