vote up 6 vote down
star
1

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.

offensive?
add comment

6 Answers:

vote up 5 vote down
check

If you look at this bug 224128, it appears that MergeSort is being used by Mozilla.

link|offensive?
add comment
vote up 4 vote down

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.

link|offensive?
add comment
vote up 1 vote down

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.

link|offensive?
comments (3)
vote up 0 vote down

After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code at http://snipr.com/4o3va.

link|offensive?
add comment
vote up 0 vote down

I've just had a look at the WebKit (Safari …) source. A comment in the code specifies the sorting used:

// "Min" sort. Not the fastest, but definitely less code than heapsort
// or quicksort, and much less swapping than bubblesort/insertionsort.

I can't make head nor tail of this. Anyway, looking at the code, there are two nested loops, i = 1…n and j = in. So the running time is quadratic.

link|offensive?
comments (1)
vote up -1 vote down

I would imagine it is implemented with quicksort. Most library sorts are.

link|offensive?
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.