Reputation: 7790
So I understand that given an array, you can sort it using a custom compare function.
So something like the following in Javascript:
var arr = [5,4,3,6,7,2];
arr.sort(function(a,b){
if (a < b)
return -1;
else if (a > b)
return 1;
else
return 0;
});
So my friend was saying that I don't need to return 0 to sort the list for this scenario. Furthermore, he says that we can return from [true,false]
instead of returning from [-1,0,1]
. Is that true?
I was trying to find a counterexample to his claim, but I could not. I can't imagine a case where the array isn't sorted properly using his code.
Here's the example that my friend gave:
var arr = [5, 4, 3, 6, 7, 2];
arr.sort(function(a, b) {
return a > b;
});
Is it good practice to return from a range of [-1,0,1]
? What is the necessity when the integers are comparable? I've noticed that this is the case across a multitude of programming languages and not just javascript. Like this example in C.
Upvotes: 0
Views: 268
Reputation: 781769
No, that is not good practice, you should follow the language specification, which says that the comparison function should return a positive value when the first element is greater than the second, a negative value when the first element is lower than the second, and 0 if they're equivalent.
What you're doing might work in some implementations, but won't be portable. Returning true
and false
is likely to result in them being coerced to 1
and 0
, respectively. And some sorting algorithms only need to know whether element A is greater than element B (for instance, the Common Lisp language specifies its SORT
function to take a boolean comparison function, so it obviously requires that the implementation use such an algorithm), so the desired result may be obtained. But if an implementation depends on tri-state logic, it won't work -- returning false
or 0
will make it think that those elements are equivalent, and it may not order them properly.
Upvotes: 1
Reputation: 164897
Tell your friend they are definitely wrong.
[0, 0, 0, -1, -1, -1, 2, 2, 2, 7, 6, 5, 4, 3].sort(function(a, b) { return a > b })
-> [2, 0, 0, -1, -1, -1, 0, 2, 2, 3, 4, 5, 6, 7]
Upvotes: 1