Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug in Array.sort()?

It's hard to believe, but this looks like a bug in Google Chrome's Javascript engine. Am I missing something?

Chrome Javascript console session:

> x = [10, 1]
> x.sort()
[1, 10]
> // OK.  But now try this.
> x = [10, 2]
> x.sort()
[10, 2]

It didn't sort it!

I'm currently running Version 24.0.1312.57 m

like image 474
Pitarou Avatar asked Feb 26 '13 07:02

Pitarou


People also ask

What does arrays sort () do?

The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

What is difference between collections sort () and arrays sort ()?

Collections. sort() Operates on List Whereas Arrays. sort() Operates on an Array. Arrays.

Does array sort sort in place?

sort works by copying the collection to an array, sorting the array, then copying the array back to the collection. Arrays. sort just sorts the array in place.

Does sort mutate array?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


2 Answers

array.sort() sorts the array in lexicographical order. That means, the values of the array are interpreted as Strings and sorted like Strings (alphabetically), not like integers.

This behavior is also described here: http://www.javascriptkit.com/javatutors/arraysort.shtml

like image 116
Uooo Avatar answered Oct 01 '22 21:10

Uooo


For those who came here figuring out what the heck is wrong with sorting in Chrome, here's an example of what unstable sort is: https://jsfiddle.net/wujpw8bo/

How to fix it:

Unstable sorting algorithms can be specially implemented to be stable. One way of doing this is to artificially extend the key comparison, so that comparisons between two objects with otherwise equal keys are decided using the order of the entries in the original input list as a tie-breaker. Remembering this order, however, may require additional time and space. https://en.wikipedia.org/wiki/Sorting_algorithm#Stability

like image 34
AlexM Avatar answered Oct 01 '22 21:10

AlexM