r/AskComputerScience • u/PresidentLap • Aug 12 '20
How does Python's sort() function work?
For more clarity, I mean does it work like a merge sort, quick sort, or some other method?
32
Upvotes
r/AskComputerScience • u/PresidentLap • Aug 12 '20
For more clarity, I mean does it work like a merge sort, quick sort, or some other method?
41
u/ggchappell Aug 12 '20 edited Aug 16 '20
Python
sortis basically Merge Sort. However, it includes a significant preprocessing step, which involves looking for increasing/decreasing runs. This is intended to improve its efficiency on real-world data. The algorithm was implemented by Tim Peters, who named it "Timsort".Also, a more general note. Despite the emphasis on it in algorithms courses, Quicksort and its variants are not really used that much any more. C++'s
std::sortis generally implemented using Introsort, a Quicksort variant, but other than that, Merge Sort & friends dominate the world of sorting -- particularly for implementations of built-in or standard-library sorting routines.There are a couple of reasons for this. First, Quicksort is not stable. If, as in Python, a programming language has just one built-in sorting method, then it will probably be stable, as client code will sometimes need that. Second, the direction that computer architecture has taken in recent decades often improves the efficiency of Merge Sort as compared to Quicksort; even C's
qsorthas a Merge-Sort-based implementation these days (the one in glibc -- last I checked).