Skip to content

Merge sort implementation #1689

@Scopula

Description

@Scopula

Specifically, line 40:

result.append((left if left[0] <= right[0] else right).pop(0))

.pop(0) method is O(n) - when you extract the first item you need to shift all remaining items to the left. Because the line is inside the while loop, the merge function is O(n^2).

My benchmark tests support this, using a randomly generated list with 10^5 items:

merge sort time: 1.5746345520019531
new merge time: 0.4434058666229248
sorted time: 0.038704633712768555

"merge sort" is current implementation, "new merge" is my merge sort implementation (using two pointer approach) and "sorted" is just the sorted() built-in function.

I tried to benchmark with 10^6 items, but the current merge sort never completed (waited maybe 15-20 sec).

If I am correct above, then I don't think an O(n log(n)) algorithm should be implemented as O(n^2).

Thank you.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions