-1

I am testing method sort() to array.
I don't understand how it works and I want to understand how it works step by step. For example:

 let array=[8, 9, 1, 2, 3, 4];
 console.log(array);
 array.sort(function (a, b) {
  console.log(`a = ${a} , b = ${b}`);
  return a - b;
 });
 console.log(array);`

I got such results:

[ 8, 9, 1, 2, 3, 4 ]    
a = 9 , b = 8; a = 1 , b = 9; a = 1 , b = 9; a = 1 , b = 8; a = 2 , b = 8; a = 2 , b = 1; a = 3 , b = 8; a = 3 , b = 2; a = 4 , b = 3; a = 4 , b = 9; a = 4 , b = 8
[ 1, 2, 3, 4, 8, 9 ]

Can you explain how is new array built step by step? How can I watch the result step by step?

desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

0

there is docs

by default it's comparing as strings, so you can give a function to compare as a numbers or whatever subproperty

with custom compareFunction you can use whatever logic:

  • negative number or zero a before b
  • positive number switch b before a

const array = [34, 10, 50, 17, 5];

source.innerHTML = JSON.stringify(array);

array.sort();
withoutParam.innerHTML = JSON.stringify(array);

array.sort((a, b) => a - b);
compareNumbers.innerHTML = JSON.stringify(array);
pre {margin-bottom: 30px;}
source: 
<pre id="source"></pre>
default compare function (as strings):
<pre id="withoutParam"></pre>
custom compare function (as numbers):
<pre id="compareNumbers"></pre>

visualisation of algorithm:

visualisation of algorithm

Michal Miky Jankovský
  • 3,089
  • 1
  • 35
  • 36
  • I know this. But I don't understand algorithm of realization compare function step by step. For example, according to your exampl: step 4 - 17 is compared with 34. Why? Why not with 50 or 10? – Andrii Artiukhov Apr 11 '21 at 08:57
  • @AndriiArtiukhov Are you interested how the js array sorting algorithm works? Is it unclear why the comparator function works the way it does? Or is the question why the comparisons happen in the order they do? I'm really unsure what you are asking – Balázs Édes Apr 11 '21 at 09:11
  • I am interested how the js array sorting algorithm works – Andrii Artiukhov Apr 11 '21 at 14:18
  • there is no standard (this is nodejs 14 latest LTS now), but each browser can use another algorithm, even for small and big arrays - there is more [SO Javascript Array.sort implementation?](https://stackoverflow.com/questions/234683/javascript-array-sort-implementation) – Michal Miky Jankovský Apr 11 '21 at 19:30
  • @AndriiArtiukhov step 4 (even step 6) uses the middle one rather than the biggest one ;) – Michal Miky Jankovský Apr 11 '21 at 19:32