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 of sorts, I'm simply interested in which algorithm the vanilla sort uses.
If you look at this bug 224128, it appears that MergeSort is being used by Mozilla. |
||||
feedback
|
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 Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or 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:
– 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.) |
|||||||||||||||||
feedback
|
After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code here. |
||||
feedback
|
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. |
|||||
feedback
|
I think that would depend on what browser implementation you are refering to. Every browser type has it's own javascript engine implementation, so it depends. You could check the sourcecode repos for Mozilla and Webkit/Khtml for different implementations. IE is closed source however, so you may have to ask somebody at microsoft. |
|||||||
feedback
|