Sorting An Number Array
When I want to sort an array, using sort() function , it is giving an alphabetically sorted array. Eg. var a=[9,10,1]; a.sort(); I'm getting a = [1,10,9] So, as per the suggesti
Solution 1:
The first version fails as they're compared like they're strings ("9"
is greater than "10"
), known as a lexicographic sort.
The custom comparator function is called with a
and b
being members of the array.
Depending on what is returned, the members are shifted. If 0
is returned, the members are considered equivalent, if a negative number, then a
is less thanb
and the inverse if it's a positive number.
If you want to visualise this, you can always log a
and b
to the console and observe how they're compared (and note how there is never any redundant comparisons made).
This is all backed by a sorting algorithm, which is left up to the implementation to choose. Chrome, for example, uses different algorithms depending on the type of members.
Post a Comment for "Sorting An Number Array"