r/oddlysatisfying • • Sep 02 '19

Learn sorting algorithm with Kronk

8.9k Upvotes

58 comments sorted by

View all comments

Show parent comments

22

u/erasmause Sep 02 '19

Usually quicksort, thoughfor pathological inputs, it can perform as poorly as bubble sort, but there are steps that can be taken to mitigate this. Heapsort is usually a bit slower in practice, but has better worst-case behavior. Neither are stable, though (a stable sitting algorithm guarantees that elements that are equivalent under the comparison function appear in the same relative order in the output as they were in the input; this can matter if the comparator only considers a subset of the value, like sorting people by age). Mergesort is in the same ballpark (better, in some specific scenarios) and is stable, but usually requires extra memory proportional to the input (some implementations reduce or eliminate this by sacrificing stability or a bit of performance).

In practice, most sort utilities provided in e.g. standard libraries are adaptive hybrids (for instance using quicksort at the top level, but once it gets down to sublists of a certain size, switching over to a simpler selection it insertion sort, or the block sort variant of mergesort).

4

u/Mr_Redstoner Oh yes Sep 03 '19

Do note that quicksort can be stable. IIRC the version that was used in Java's Arrays.sort was.

1

u/i_rnb Sep 03 '19

Are you sure about block sort? I thought Timsort is more popular among standard libraries.

1

u/gurenkagurenda Sep 03 '19

The only common languages I know of that use Timsort in their standard libraries are Python and Java. AFAIK, Ruby (at least MRI), PHP, and most JS engines still use quicksort. .NET apparently uses introsort, another hybrid approach. I actually don't know what standard libraries the previous commenter is talking about which use block sort.

3

u/erasmause Sep 03 '19

I wasn't claiming any specific library used it, just giving it as an example of am adaptive hybrid. Sorry for the confusion.