Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Python's built in sort() method

What algorithm is the built in sort() method in Python using? Is it possible to have a look at the code for that method?

like image 478
Johannes Avatar asked Oct 08 '22 14:10

Johannes


People also ask

What is Python's built-in sort?

Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here.

What is sort method in Python?

Definition and Usage. 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.

What is the use of sort ()?

The SORT function sorts the contents of a range or array. In this example, we're sorting by Region, Sales Rep, and Product individually with =SORT(A2:A17), copied across cells F2, H2, and J2. Note: This function is currently available to Microsoft 365 subscribers in Current Channel.

How is sort method implemented in Python?

In early python-versions, the sort function implemented a modified version of quicksort. However, it was deemed unstable and as of 2.3 they switched to using an adaptive mergesort algorithm.


3 Answers

Sure! The code's here, starting with function islt and proceeding for QUITE a while;-). As Chris's comment suggests, it's C code. You'll also want to read this text file for a textual explanation, results, etc etc.

If you prefer reading Java code than C code, you could look at Joshua Bloch's implementation of timsort in and for Java (Joshua's also the guy who implemented, in 1997, the modified mergesort that's still used in Java, and one can hope that Java will eventually switch to his recent port of timsort).

Some explanation of the Java port of timsort is here, the diff is here (with pointers to all needed files), the key file is here -- FWIW, while I'm a better C programmer than Java programmer, in this case I find Joshua's Java code more readable overall than Tim's C code;-).

like image 146
Alex Martelli Avatar answered Oct 17 '22 16:10

Alex Martelli


I just wanted to supply a very helpful link that I missed in Alex's otherwise comprehensive answer: A high-level explanation of Python's timsort (with graph visualizations!).

(Yes, the algorithm is basically known as Timsort now)

like image 40
u0b34a0f6ae Avatar answered Oct 17 '22 15:10

u0b34a0f6ae


In early python-versions, the sort function implemented a modified version of quicksort. However, it was deemed unstable and as of 2.3 they switched to using an adaptive mergesort algorithm.

like image 10
Silfverstrom Avatar answered Oct 17 '22 15:10

Silfverstrom