Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of the sorted() function?

I have a list of lists and I am sorting them using the following

data=sorted(data, key=itemgetter(0)) 

Was wondering what is the runtime complexity of this python function?

like image 412
Read Q Avatar asked Jan 21 '13 07:01

Read Q


People also ask

What is time complexity of sort () in C++?

Time ComplexityBest Case – O(N log N) Average Case- O(N log N) Worse Case- O(N log N)

What is the time complexity of sorted?

sort uses two sorting algorithms. One is a modification of Quicksort named dual-pivot quicksort, the other an adaptation of MergeSort named Timsort. Both have a time complexity of O(n log n) , where n is the total number of items in the array.

What does sorted () use in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

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.


Video Answer


2 Answers

Provided itemgetter(0) is O(1) when used with data, the sort is O(n log n) both on average and in the worst case.

For more information on the sorting method used in Python, see Wikipedia.

like image 98
NPE Avatar answered Oct 18 '22 03:10

NPE


sorted is like sort except that the first builds a new sorted list from an iterable while sort do sort in place. The main difference will be space complexity.

like image 39
blackmath Avatar answered Oct 18 '22 02:10

blackmath