Skip to content

Commit 5d5a503

Browse files
ryuta69cclauss
authored andcommitted
Add merge insertion sort (TheAlgorithms#2211)
* Add merge insertion sort * Fix python naming conventions * Add wikipedia link * Add type hint * Fix python to python3 Co-authored-by: Christian Clauss <[email protected]> * Refactor doubled process in if-condition into one outside of if-condition Co-authored-by: Christian Clauss <[email protected]> * Refactor make python3 prior to python Co-authored-by: Christian Clauss <[email protected]> * Fix name of is_surplus into has_last_odd_item * Add comment * Fix long comment to shorten Co-authored-by: Christian Clauss <[email protected]>
1 parent 6574b43 commit 5d5a503

File tree

1 file changed

+179
-0
lines changed

1 file changed

+179
-0
lines changed

sorts/merge_insertion_sort.py

+179
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
"""
2+
This is a pure Python implementation of the merge-insertion sort algorithm
3+
Source: https://en.wikipedia.org/wiki/Merge-insertion_sort
4+
5+
For doctests run following command:
6+
python3 -m doctest -v merge_insertion_sort.py
7+
or
8+
python -m doctest -v merge_insertion_sort.py
9+
10+
For manual testing run:
11+
python3 merge_insertion_sort.py
12+
"""
13+
14+
from typing import List
15+
16+
17+
def merge_insertion_sort(collection: List[int]) -> List[int]:
18+
"""Pure implementation of merge-insertion sort algorithm in Python
19+
20+
:param collection: some mutable ordered collection with heterogeneous
21+
comparable items inside
22+
:return: the same collection ordered by ascending
23+
24+
Examples:
25+
>>> merge_insertion_sort([0, 5, 3, 2, 2])
26+
[0, 2, 2, 3, 5]
27+
28+
>>> merge_insertion_sort([99])
29+
[99]
30+
31+
>>> merge_insertion_sort([-2, -5, -45])
32+
[-45, -5, -2]
33+
"""
34+
35+
def binary_search_insertion(sorted_list, item):
36+
left = 0
37+
right = len(sorted_list) - 1
38+
while left <= right:
39+
middle = (left + right) // 2
40+
if left == right:
41+
if sorted_list[middle] < item:
42+
left = middle + 1
43+
break
44+
elif sorted_list[middle] < item:
45+
left = middle + 1
46+
else:
47+
right = middle - 1
48+
sorted_list.insert(left, item)
49+
return sorted_list
50+
51+
def sortlist_2d(list_2d):
52+
def merge(left, right):
53+
result = []
54+
while left and right:
55+
if left[0][0] < right[0][0]:
56+
result.append(left.pop(0))
57+
else:
58+
result.append(right.pop(0))
59+
return result + left + right
60+
61+
length = len(list_2d)
62+
if length <= 1:
63+
return list_2d
64+
middle = length // 2
65+
return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:]))
66+
67+
if len(collection) <= 1:
68+
return collection
69+
70+
"""
71+
Group the items into two pairs, and leave one element if there is a last odd item.
72+
73+
Example: [999, 100, 75, 40, 10000]
74+
-> [999, 100], [75, 40]. Leave 10000.
75+
"""
76+
two_paired_list = []
77+
has_last_odd_item = False
78+
for i in range(0, len(collection), 2):
79+
if i == len(collection) - 1:
80+
has_last_odd_item = True
81+
else:
82+
"""
83+
Sort two-pairs in each groups.
84+
85+
Example: [999, 100], [75, 40]
86+
-> [100, 999], [40, 75]
87+
"""
88+
if collection[i] < collection[i + 1]:
89+
two_paired_list.append([collection[i], collection[i + 1]])
90+
else:
91+
two_paired_list.append([collection[i + 1], collection[i]])
92+
93+
"""
94+
Sort two_paired_list.
95+
96+
Example: [100, 999], [40, 75]
97+
-> [40, 75], [100, 999]
98+
"""
99+
sorted_list_2d = sortlist_2d(two_paired_list)
100+
101+
"""
102+
40 < 100 is sure because it has already been sorted.
103+
Generate the sorted_list of them so that you can avoid unnecessary comparison.
104+
105+
Example:
106+
group0 group1
107+
40 100
108+
75 999
109+
->
110+
group0 group1
111+
[40, 100]
112+
75 999
113+
"""
114+
result = [i[0] for i in sorted_list_2d]
115+
116+
"""
117+
100 < 999 is sure because it has already been sorted.
118+
Put 999 in last of the sorted_list so that you can avoid unnecessary comparison.
119+
120+
Example:
121+
group0 group1
122+
[40, 100]
123+
75 999
124+
->
125+
group0 group1
126+
[40, 100, 999]
127+
75
128+
"""
129+
result.append(sorted_list_2d[-1][1])
130+
131+
"""
132+
Insert the last odd item left if there is.
133+
134+
Example:
135+
group0 group1
136+
[40, 100, 999]
137+
75
138+
->
139+
group0 group1
140+
[40, 100, 999, 10000]
141+
75
142+
"""
143+
if has_last_odd_item:
144+
pivot = collection[-1]
145+
result = binary_search_insertion(result, pivot)
146+
147+
"""
148+
Insert the remaining items.
149+
In this case, 40 < 75 is sure because it has already been sorted.
150+
Therefore, you only need to insert 75 into [100, 999, 10000],
151+
so that you can avoid unnecessary comparison.
152+
153+
Example:
154+
group0 group1
155+
[40, 100, 999, 10000]
156+
^ You don't need to compare with this as 40 < 75 is already sure.
157+
75
158+
->
159+
[40, 75, 100, 999, 10000]
160+
"""
161+
is_last_odd_item_inserted_before_this_index = False
162+
for i in range(len(sorted_list_2d) - 1):
163+
if result[i] == collection[-i]:
164+
is_last_odd_item_inserted_before_this_index = True
165+
pivot = sorted_list_2d[i][1]
166+
# If last_odd_item is inserted before the item's index,
167+
# you should forward index one more.
168+
if is_last_odd_item_inserted_before_this_index:
169+
result = result[: i + 2] + binary_search_insertion(result[i + 2 :], pivot)
170+
else:
171+
result = result[: i + 1] + binary_search_insertion(result[i + 1 :], pivot)
172+
173+
return result
174+
175+
176+
if __name__ == "__main__":
177+
user_input = input("Enter numbers separated by a comma:\n").strip()
178+
unsorted = [int(item) for item in user_input.split(",")]
179+
print(merge_insertion_sort(unsorted))

0 commit comments

Comments
 (0)