0

I was trying to understand the steps of a sorting function so I know when a[1] - b[1] and b[0] - a[0] are performed, so I inserted a console.log in my compare function. I am more confused as I don't see a pattern, for example why is [7, 1] [4, 4] logged twice?

const sortFunc = (a, b) => {
    console.log(a,b)

    return a[0] === b[0] ? a[1] - b[1] : b[0] - a[0];
}

let arr = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

arr.sort(sortFunc) // sorted arr is [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]

the console logs are as follow:

[4, 4] [7, 0]
[7, 1] [4, 4]
[7, 1] [4, 4]
[7, 1] [7, 0]
[5, 0] [7, 1]
[5, 0] [4, 4]
[6, 1] [5, 0]
[6, 1] [7, 1]
[5, 2] [6, 1]
[5, 2] [4, 4]
[5, 2] [5, 0]
tausabao
  • 247
  • 1
  • 3
  • 11
  • 2
    The sorting algorithm is not specified and thus implementation-dependant. Every implementation might use different algorithm(s) which might also differ based on the size of your array. You should probably read about sorting algorithms instead of making sense of these logs. – str Apr 11 '20 at 07:32
  • Also relevant: [How does Javascript's sort() work?](https://stackoverflow.com/questions/1494713/how-does-javascripts-sort-work) and what I personally found very insightful about the sorting algorithms: [Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?](https://stackoverflow.com/questions/24080785/sorting-in-javascript-shouldnt-returning-a-boolean-be-enough-for-a-comparison) – VLAZ Apr 11 '20 at 07:38

0 Answers0