r/AskComputerScience • • 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

12 comments sorted by

41

u/ggchappell Aug 12 '20 edited Aug 16 '20

Python sort is 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::sort is 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 qsort has a Merge-Sort-based implementation these days (the one in glibc -- last I checked).

8

u/wescotte Aug 12 '20

Can you elaborate on how quicksort isnt stable? You mean it can have unintended consequences/crash? Or more like its runtime performance is unstable?

34

u/wlu56 Aug 12 '20

"stability" of a sorting algorithm does not relate with correcness/reliability of the sorting algorithm. instead it means - if two objects have the same value, then they maintain their relative ordering before and after sorting.

real life example: suppose you are sorting persons by their age in a straight line. if both persons A and B are age 20. then after sorting, both A and B should maintain their relative order before and after sorting. if this holds, then the sort is stable.

14

u/ggchappell Aug 12 '20

Can you elaborate on how quicksort isnt stable?

When we talk about algorithms that rearrange items in a list, stable means that the relative order of items that compare equivalent will not be changed.

For example, suppose we have a list of names: ..., Fred Jones, ..., Alice Jones, .... If we sort these by last name, then "Fred Jones" and "Alice Jones" compare as equivalent, since their last names are the same. Therefore, a stable sorting algorithm will always keep "Fred Jones" before "Alice Jones" in the final sorted list.

Merge Sort and Insertion Sort are stable. Quicksort, Introsort, Shell Sort, and Heap Sort are not stable. (To be a bit more accurate, making these stable generally compromises their efficiency, so they are are almost always implemented in a non-stable manner.)

1

u/wescotte Aug 12 '20

Thanks!

I'm struggling to think of any real world reasons why you would want/need to retain the original ordering if only sorting by a single key though... Do you know any off the top of your head?

8

u/Mukhasim Aug 12 '20

One reason you might want a stable sort is if, for whatever reason, you need to guarantee that you always get the same output for a given input. An unstable sort can give you different outputs depending on the particularities of the implementation.

I once wrote a configuration system where multiple entries for the same key were supposed to be resolved according to particular rules. The last occurrence had to take precedence except when one was marked with a higher priority. I implemented that by sorting by priority, but the sort had to be stable because the original order mattered.

Another possible reason is if you don't want the collection to be reordered when it's already sorted.

6

u/apendleton Aug 12 '20

To give a non-CS example, you can imagine that you're working with a table, say in Excel or on Wikipedia, where you can sort by columns. If you want your list sorted by column A then column B (so like, where A is tied, sort on B), you can first sort by B, then sort by A, if your sort is stable (it is in Excel, probably specifically to make this possible) -- that way, when the second sort sorts by A, if A is tied, things end up sorted by B within each A tie, since they were already sorted that way before and retain their original order.

Of course, if you're writing code instead of using Excel, even with an unstable sort you could sort on the tuple (A, B) to achieve the same effect. One situation where this property might still be useful, though, is if your data is already sorted by B (because it comes out of the database that way or whatever): then you can get a list sorted on (A, B) just by sorting on A.

2

u/dnswblzo Aug 12 '20

It would be annoying if spreadsheets didn't have a stable sort. If you sort your data using a single column as a key, and that column has duplicate values, it's nice if every row that shares a value in that column retains its relative position.

For example, say you have a spreadsheet with items that are already sorted by alphabetical order. You add a column where you put a rank by each item - 3 if the item is great, 2 if it's so-so, and 1 if it's bad. Then if you sort the data by the rank column, it's nice if all the items with the same rank stay in alphabetical order.

Granted in Excel when sorting you can tell it to sort by one column first and then another, but that's extra work. Also in other situations there might be meaning to the original ordering of the data but no way to sort it again to get back to that ordering.

1

u/ACoderGirl Aug 13 '20

You often don't sort things based on their full value, but rather by some subfield. eg, sorting a list of people by name. The list may still have other attributes like age and email. Picture how annoying it would be for a UI to sometimes shuffle around people who have the same name.

4

u/[deleted] Aug 12 '20

Timsort is also used in C++ and Java IIRC.

2

u/CptCap Aug 12 '20

Java uses Timsort, C++ uses an adaptive quick sort (introsort or pdqsort) but provides other sorting methods.

Quicksort (and derivatives) are in-place, so they do not need to extra allocate memory, which might be important if you are using C++. It also tend to be faster but its instability makes it a poor fit for a default/"one fits all" implementation. (C++ puts performance above usability in most cases, which is why std::sortis quicksort)

3

u/proskillz Aug 13 '20

Java uses Timsort for objects and quicksort for primatives.