Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sorting complexity on sorted list

Tags:

python

sorting

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.

like image 858
Bartosz Marcinkowski Avatar asked May 22 '14 14:05

Bartosz Marcinkowski


People also ask

What is the time complexity for a sorted list?

SortedList provides O(log n) time complexity for KeyValuePair retrieval. Unlike SortedDictionary that is implemented with Binary Search Tree, SortedList is implemented with two internal arrays for keys and values. Therefore, insertion operation and removal operation take O(n), which are slower than SortedDictionary.

Is sort () or sorted () faster?

Sort vs Sorted Performance Here, sort() method is executing faster than sorted() function. Here, sorted() function method is executing faster than sort() function. There is also a difference in execution time in both cases.

Is Python sorted () stable?

sort() and sorted() in python are “stable sorts”, meaning that it'll preserve the existing order when faced with a tie.

Which sorting algorithm is used in Python sorted?

Python's default sort uses Tim Sort, which is a combination of both merge sort and insertion sort. Implementation of that will be covered in another article.


1 Answers

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.

like image 51
mgilson Avatar answered Oct 05 '22 18:10

mgilson