0

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.

Community
  • 1
  • 1
Ehtesh Choudhury
  • 7,452
  • 5
  • 42
  • 48
  • `});` (twice!) looks wrong. – wildplasser Sep 27 '13 at 00:24
  • 1
    According to the documentation, your friend is wrong. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Phil Sep 27 '13 at 00:27
  • 1
    Note that they don't have to be just `[-1, 0, 1]`, they can be any negative, 0, or any positive value. This allows you to do `return a - b;`. – Barmar Sep 27 '13 at 00:29
  • What @Phil said, and you should use the keyword `var` unless you want `arr` to be global. – StackSlave Sep 27 '13 at 00:30

2 Answers2

1

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]
Phil
  • 157,677
  • 23
  • 242
  • 245
1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612