118
votes

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

3
Of course it's possible to look at the code for the method - Python is an open-source project. The method is probably implemented in C, however, so you'll have to know a bit about C to make any sense of it. - Chris Lutz
Does the version matter? - meder omuraliev
@melder: No =) I just want to have a look at a pro algorithm :P @chris: how? - Johannes
Download the source code to the Python interpreter. I don't know where they implement the sort() method, or what the formatting to the interpreter is, but it's got to be in there somewhere, and I bet it's implemented in C for speed concerns. - Chris Lutz
Here is an example of it being used - Hari Ganesan

3 Answers

134
votes

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;-).

36
votes

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)

10
votes

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.