Python sorting complexity on sorted list

This is entirely implementation dependent. All that python guarantees is that the builtin sorting algorithm is stable (elements which compare equal retain their relative ordering). An implementation could even use a stable bubble sort if it wanted to …

Cpython uses TimSort (a hybrid of insertion sort an mergesort) which I believe has O(N) complexity if the input is already sorted — It picks up the best case performance of insertion sort and the worst case performance of mergesort (O(NlogN)).

And if you’re curious about the implementation, the source code has a very nice description.

Leave a Comment