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.
Join them; it only takes a minute:
|
||||
|
If you look at this bug 224128, it appears that MergeSort is being used by Mozilla. |
|||||||||||||
|
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.) |
|||||||||||||||||||||
|
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. |
|||||
|
After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code here. |
||||
|
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. |
|||||||||||||
|
There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome's v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays. https://github.com/v8/v8/blob/master/src/js/array.js From Lines 807 - 891
|
|||
|
protected by Praveen Apr 21 at 12:33
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?