def merge_sort(L: list) -> list: """Sort the items in L from smallest to largest using Merge Sort. """ if len(L) <= 1: return L mid = len(L) // 2 left = L[:mid] right = L[mid:] left = merge_sort(left) right = merge_sort(right) return merge(left,right) def merge(left: list, right: list) -> list: """Merge two sorted lists into one sorted list. """ result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) while left: result.append(left.pop(0)) while right: result.append(right.pop(0)) return result if __name__ == "__main__": aList = [4, 1, 7, 6, 5, 3, 8, 2] result = merge_sort(aList) print(result)
The merge
functions uses the pop
and append
methods.
How much time will these two methods take?
pop(0)
take O(n)
and pop()
take O(1)
.
pop()
removes the last element.
append()
take O(1)
.
append()
adds element at the end.