Home > Mobile >  Why does compare function of sort() work like that?
Why does compare function of sort() work like that?

Time:10-05

I've read in documentation about compare function's work. This callback function can have 2 parameters. There are 3 "if" for them:

  • If compareFunction(a, b) returns a value > than 0, sort b before a.
  • If compareFunction(a, b) returns a value < than 0, sort a before b.
  • If compareFunction(a, b) returns 0, a and b are considered equal.

So, as far as I see, if compare function returns a value less than zero, compare algorithm do nothing (a and b stay in the same places). And if this function returns a value more than zero, a and b switches (b goes first).

Okay, that's understandable. But why my code below works like that?

let arr1 = [9, 3, 6, 7, 1];
console.log(arr1.sort((a, b) => 1)); //1 > 0 -> compare function should switch elements

let arr2 = [9, 3, 6, 7, 1];
console.log(arr2.sort((a, b) => -1)); //-1 < 0 -> compare function shouldn't switch elements

CodePudding user response:

If the compare function returns the wrong answer when asked the fundamental question which value is less than the other, why wouldn't you expect the wrong answer from the function that depends on it?

The sort algorithm probably makes the equivalent of two passes before it is done, and ends up returning the values back to its place on the second pass.

I say equivalent - it might be going through once, but on the lower index elements it sorts it one way, and on the higher elements it goes the other way.

For the second case, it considers the top elements sorted, and then the bottom elements it thinks it has to switch.

But sorts all work differently. A merge sort might depend on how many times it is divisible by 2. A quick sort might depend on the pivot position. An insertion sort might depend on number of elements being even or odd.

CodePudding user response:

Your interpreation of the docs is wrong.

You say

-1 means elements should stay in the same place.

That's wrong, the docs just state that -1 means a should be sorted before b.

Depending on the underlying sorting algorithm, there is no guarantee whatsoever that, when calling the comparefunction with parameters a and b that a is currently before b in the array. Ie imagine an array [1,2,3]. It may be possible that the compare function is called with parameters (3, 1) or (1,3). But if you return -1 in the first case, 1 and 3 will indeed switch positions. And vice versa, if you return 1 in the second case, 1 and 3 will again switch places.

  • Related