Which algorithm does the JavaScript Array#sort()
function use? I understand that it can take all manner of arguments and functions to perform different kinds o
As of V8 v7.0 / Chrome 70, V8 uses TimSort, Python's sorting algorithm. Chrome 70 was released on September 13, 2018.
See the the post on the V8 dev blog for details about this change. You can also read the source code or patch 1186801.
If you look at this bug 224128, it appears that MergeSort is being used by Mozilla.
The ECMAscript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox's sort() is not stable (in the sorting sense of the word) when sorting a map. IE's sort() is stable.
I've just had a look at the WebKit (Chrome, Safari …) source. Depending on the type of array, different sort methods are used:
Numeric arrays (or arrays of primitive type) are sorted using the C++ standard library function std::qsort which implements some variation of quicksort (usually introsort).
Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or qsort
if no merge sort is available.
For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either selection sort (which they call “min” sort) or, in some cases, it sorts via an AVL tree. Unfortunately, the documentation here is rather vague so you’d have to trace the code paths to actually see for which types which sort method is used.
And then there are gems like this comment:
// FIXME: Since we sort by string value, a fast algorithm might be to use a
// radix sort. That would be O(N) rather than O(N log N).
– Let’s just hope that whoever actually “fixes” this has a better understanding of asymptotic runtime than the writer of this comment, and realises that radix sort has a slightly more complex runtime description than simply O(N).
(Thanks to phsource for pointing out the error in the original answer.)
JavaScript's Array.sort() function has internal mechanisms to selects the best sorting algorithm ( QuickSort, MergeSort, etc) on the basis of the datatype of array elements.
After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code here.