When calling sort()
on a list in Python, passing cmp=f
slows down the sort. Does passing reverse=True
affect the efficiency of the sort in any way (or is it identical to sorting without reversing)?
Sorting Basics You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient. Another difference is that the list.sort() method is only defined for lists.
Setting reverse = True sorts the list in the descending order.
True to its name, Quicksort is very fast. Although its worst-case scenario is theoretically O(n2), in practice, a good implementation of Quicksort beats most other sorting implementations. Also, just like merge sort, Quicksort is straightforward to parallelize.
Thus sort() method is used to arrange a list in either Ascending or Descending order. One more important thing to remember here is that sort() method changes the order of the list permanently. If you want to change the order of the list temporarily, then you need to use sorted() function.
From my benchmarks, there appears to be a small difference:
import timeit
setup = """
import random
random.seed(1)
l = range(10000)
random.shuffle(l)
"""
run1 = """
sorted(l)
"""
run2 = """
sorted(l, reverse=True)
"""
n1 = timeit.timeit(run1, setup, number=10000)
n2 = timeit.timeit(run2, setup, number=10000)
print n1, n2
print (n2/n1 - 1)*100,"%"
Results in (on my machine):
38.8531708717 41.2889549732
6.26920286513 %
The same run, but for a list of 1000 elements:
2.80148005486 2.74061703682
-2.17253083528 %
# ...another round...
2.90553498268 2.86594104767
-1.36270722083 %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With