1

I don't believe this is a duplicate of this How does Javascript's sort() work?

let arr = [3, 4, 2, 1];
arr.sort((second,first) => {
  console.log([first, second]);
  if (first>second) {
    return -1; // switch them
  }
  return 0; // don't switch them

});
console.log(arr);

This returns

[ 3, 4 ]
[ 4, 2 ]
[ 4, 2 ] <---- Why is this output twice?
[ 3, 2 ]
[ 3, 1 ]
[ 2, 1 ]
[ 1, 2, 3, 4 ]

I am trying to figure out what algorithm NodeJS (14.4.0) is using for Array.sort with my input?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
lindsaymacvean
  • 4,419
  • 2
  • 19
  • 21
  • 1
    Your sort callback could cause inconsistent results because you are returning `0` when `second > first`. Try adding a `else if (second > first) { return 1 }`. – adiga Feb 18 '21 at 14:08
  • 1
    Also, it's pure evil to name the first parameter as `second` and second parameter as `first`. I was wondering why the `sort` was working the wrong way :) – adiga Feb 18 '21 at 14:10
  • Related: [Sorting in JavaScript: Should every compare function have a “return 0” statement?](https://stackoverflow.com/questions/20883421) – adiga Feb 18 '21 at 14:12
  • @adiga also relevant: [Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?](https://stackoverflow.com/q/24080785) – VLAZ Feb 18 '21 at 14:13
  • @adiga I think that was because the order of the items in the array. Not my code originally :) – lindsaymacvean Feb 18 '21 at 16:06

1 Answers1

0

As a note in this post, the v8 engine apparently uses Timsort for sorting:

https://v8.dev/blog/array-sort#timsort

Joe
  • 41,484
  • 20
  • 104
  • 125