简体   繁体   中英

Python sorting complexity on sorted list

What is the sort(already_sorted_list) complexity in Python? Does Python check if given iterable is sorted, or do I have to do it by myself? I could not find it anywhere in the docs.

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.

Python's sort is called timsort . Its average case performance is O(nlog(n)). It performs really well with pre-sorted lists because it's implementation is designed to seek out runs of sorted elements in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM