Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime of sorted() on an already sorted list?

Tags:

python

Just curious, will the built-in sorted() function just note a list is already sorted and return the same list in constant time?

x = [1, 2, 3, 4, 5]
y = sorted(x)
like image 313
Nick Avatar asked Nov 29 '25 14:11

Nick


1 Answers

No. It will create a new list and add the values from the existing list in sorted order which in your case is already sorted. It will walk through the entire existing list in O(n) times for a list of length n. So it will not return a list in constant time.

And there is no way the sorted() function can know that list is sorted until the entire list is iterated over by it which obviously cannot be done in constant time.

like image 107
Yousaf Avatar answered Dec 02 '25 04:12

Yousaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!