Lonely
Lonely

Reputation: 613

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 suggestions I used another function

function sortfunction(x, y){
    return (x - y) //causes an array to be sorted numerically and ascending
}

and then used

a.sort(sortfunction);

to get the right result.

Can anyone explain in detail, how this works?

Upvotes: 0

Views: 142

Answers (1)

alex
alex

Reputation: 490143

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 than b 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.

Upvotes: 3

Related Questions