Why is my MergeSort so slow in Python?

前端 未结 4 1920
春和景丽
春和景丽 2021-01-14 15:20

I\'m having some troubles understanding this behaviour. I\'m measuring the execution time with the timeit-module and get the following results for 10000 cyc

4条回答
  •  日久生厌
    2021-01-14 15:55

    list.pop(0) pops the first element and has to shift all remaining ones, this is an additional O(n) operation which must not happen.

    Also, slicing a list object creates a copy:

    left = array[:len(array)/2]
    right = array[len(array)/2:]
    

    Which means you're also using O(n * log(n)) memory instead of O(n).

    I can't see BubbleSort, but I bet it works in-place, no wonder it's faster.

    You need to rewrite it to work in-place. Instead of copying part of original list, pass starting and ending indexes.

提交回复
热议问题