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
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.
Collections. sort() Operates on List Whereas Arrays. sort() Operates on an Array. Arrays.
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.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With