Skip to content

Commit c2b2c4d

Browse files
authored
merge_sort.py
Here after looking the actual code, I found out that the storing the sorted element in the result one by one on comparing two lists, that is left and right, it was using the pop() function for the seek of reducing the line of code. I wanted to alert about the pop function, as pop function in python extract the element on particular valid index from the list, mentioning in argument (by default the last element of the list). But pop off the first element takes O(n) complexity (where n is the length of the list) which leads to extra time complexity, also kind of making worst case for already sorted list. Also, there is no need of extracting element, instead we just access the element through pointer ( left_index , right_index )
1 parent 2cbe01a commit c2b2c4d

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

sorts/merge_sort.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,20 @@ def merge(left: list, right: list) -> list:
3737
:return: Merged result
3838
"""
3939
result = []
40-
while left and right:
41-
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
42-
result.extend(left)
43-
result.extend(right)
40+
left_length = len(left)
41+
right_length = len(right)
42+
left_index = right_index = 0
43+
44+
while (left_index < left_length) and (right_index < right_length):
45+
if left[left_index] < right[right_index]:
46+
result.append(left[left_index])
47+
left_index += 1
48+
else:
49+
result.append(right[right_index])
50+
right_index += 1
51+
52+
result.extend(left[left_index : ])
53+
result.extend(right[right_index : ])
4454
return result
4555

4656
if len(collection) <= 1:

0 commit comments

Comments
 (0)