Javascript sorting - weird behavior, any idea?

If i do

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'].sort( function(a,b){ return a.length - b.length } )

displays

["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"]

But when I do (adds one 'l' element to the end)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l'].sort( function(a,b){ return a.length - b.length } )

displays

["f", "a", "c", "d", "e", "b", "g", "h", "i", "k", "l"]

Is there any specific reason why this is happening or is it just a fad?

PS: related to this question . I tested it on chrome, and it has been listening to me since yesterday :)

+4
source share
4

V8, - , Chrome <= 10 quicksort .

, .. , , . , - .

:

( , , )

.

+4

(), (.. 1). . , .

+1

, , (, quicksort). , javascript .

, 0 , . , .

, , , quicksort . , , , .

0

This is due to Quicksort implemented in the JavaScript VM. Your user-defined function returns 0 anyway, because all your string lengths are 1, so basically it's simple:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'].sort( function(a,b){ return 0 } )

-1
source

All Articles