@@ -67,29 +67,102 @@ def merge(left, right):
67
67
if len (collection ) <= 1 :
68
68
return collection
69
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
+ """
70
76
two_paired_list = []
71
77
has_last_odd_item = False
72
78
for i in range (0 , len (collection ), 2 ):
73
79
if i == len (collection ) - 1 :
74
80
has_last_odd_item = True
75
81
else :
82
+ """
83
+ Sort two-pairs in each groups.
84
+
85
+ Example: [999, 100], [75, 40]
86
+ -> [100, 999], [40, 75]
87
+ """
76
88
if collection [i ] < collection [i + 1 ]:
77
89
two_paired_list .append ([collection [i ], collection [i + 1 ]])
78
90
else :
79
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
+ """
80
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
+ """
81
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
+ """
82
129
result .append (sorted_list_2d [- 1 ][1 ])
83
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
+ """
84
143
if has_last_odd_item :
85
144
pivot = collection [- 1 ]
86
145
result = binary_search_insertion (result , pivot )
87
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] so that you can avoid unnecessary comparison.
151
+
152
+ Example:
153
+ group0 group1
154
+ [40, 100, 999, 10000]
155
+ ^ You don't need to compare with this as 40 < 75 is already sure.
156
+ 75
157
+ ->
158
+ [40, 75, 100, 999, 10000]
159
+ """
88
160
is_last_odd_item_inserted_before_this_index = False
89
161
for i in range (len (sorted_list_2d ) - 1 ):
90
162
if result [i ] == collection [- i ]:
91
163
is_last_odd_item_inserted_before_this_index = True
92
164
pivot = sorted_list_2d [i ][1 ]
165
+ # If last_odd_item is inserted before the item's index, you should forward index one more.
93
166
if is_last_odd_item_inserted_before_this_index :
94
167
result = result [: i + 2 ] + binary_search_insertion (result [i + 2 :], pivot )
95
168
else :
0 commit comments