About Python's built in sort() method

69,499

Solution 1

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

Solution 2

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)

Solution 3

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.

Share:
69,499
Johannes
Author by

Johannes

Updated on July 08, 2022

Comments

  • Johannes
    Johannes almost 2 years

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

  • Alex Martelli
    Alex Martelli over 14 years
    @Chris, "Browse Python sources" is a shortcut in all of my browsers' bookmark bars -- it points to svn.python.org/view/python/trunk ;-).
  • visual_learner
    visual_learner over 14 years
    I want to know what the function list_ass_item() does. :)
  • Alex Martelli
    Alex Martelli over 14 years
    Performs assignment to an item of the list (just like list_ass_slice performs assignment to a slice of the list), nothing to do with sorting. I guess the abbreviation of "assignment" makes the name funny...
  • Tim Peters
    Tim Peters over 10 years
    The current version of listsort.txt adds some notes that address common confusions.
  • Tony Suffolk 66
    Tony Suffolk 66 almost 4 years
    quicksort isn't 'deemed unstable' - by the commonly used definitions, quicksort is unstable - that is the original ordering of two objects is not preserved, if they are equal during this sort. Having an unstable sort algorithm means that you have to come up with all sorts of 'magic' to sensibly sort data with multiple criteria, rather than then simply being able to chain sort calls - in timsort if you want to sort by D.O.B and then name, you simply sort by name first, and then D.O.B. You can't do that with quicksort