Reputation: 16140
Usually while sorting you do:
if (x < y) return -1
else if (x > y) return 1
else return 0
or
return ((x > y) ? 1 : ((x < y)) ? -1 : 0))
Two comparisons for what seems can be accomplished with only one. In assembly all you have to do is subtract both to a register, check if is negative, check if is zero. The problem is in javascript if we were to subtract:
var sub = (x - y);
return (sub == 0 ? 0 : ((sub < 0) ? -1 : 1))
This would end up with even more code to be executed.
So, some questions:
Upvotes: 1
Views: 502
Reputation: 104810
sorting alphabetically can be done with array.sort(), but if you want a case insensitive sort you do need to test if the strings are the same, or if one is greater or less than the other.
array.sort(function(a,b){
a=a.toLowerCase();
b=b.toLowerCase();
if(a==b) return 0;
return a>b? 1:-1;
}
Worrying about an extra comparison is beside the point here, the conversion toLowerCase is what eats up cycles. SO don't use toLowerCase unless you need it.
Numbers, as has been shown, are simple-
array.sort(function(a,b){ return a-b});
Upvotes: 1
Reputation: 121
Usually the sort algorithm is not looking specifically for -1 or +1, just <0 or >0. The comparison function in this case could be as simple as
return x - y ;
Upvotes: 1
Reputation: 237975
In Javascript, sort
does not have to return -1
, 0
or 1
. It can return any number. This means that you only need to subtract one number from the other to compare them.
The MDC docs for Array.sort
suggest this implementation:
function compareNumbers(a, b)
{
return a - b;
}
var nums = [34, 56, 1, 42, 63];
nums.sort(compareNumbers);
// [1, 34, 42, 56, 63]
Upvotes: 2