Explination of arguments for .sort()

How do the arguments a and b iterate through the array of this example below?

``````var array = [1, 12, 21, 2];
array.sort(function(a, b) {
return a - b;
});
``````

I understand that is (a - b) is positive it will move the number to the right, but then do a and b move over to the next numbers or how does that work? I’ve watch about half a dozen videos and no one goes to explain how this works

So for example, if we run this I’m assuming it goes like this a = 1, b = 12, 1 - 12 = -11 so 1 stays in place as it is a negative number.

Then what? Does a = 12 and then b = 21 which would then still be negative. So ok, this is working so far… this is where I get hung up though. Again, I’m assuming a and b will move over one soooo a = 21 and b = 2 which gives us a positive number.

This will move 2 to the left so now we have 1, 12, 2, 21, and this is where I’m lost. So what is the value of a and be now that we have come to the end of this? Does it start from the beginning? Are we back to a = 1 and b = 12 then shifting over each time until we’ve reach then end? Please help

In addition to this I just used the visual editor to see how this works, and it was rather confusing. Doing the revers b - a is way more confusing as well as there doesn’t seem to be any logical order for how it picks and chooses a and b once it starts moving number around. Please help!

https://goo.gl/O7GWSW

I think you are looking for sorting algorithm.
The visual looks pretty cool.

If you try to manually write your own sorting algorithm. You’ll encounter a problem that you have to repeat the sort just to make sure that all the values fall onto the same place.

``````1, 12, 21, 2 -> Compare 1 and 12
12, 1, 21, 2 -> Compare 1 and 21
12, 21, 1, 2 -> Compare 12 and 21
21, 12, 1, 2 -> Compare 1, 2
21, 12, 2, 1
``````

I did a little bit of digging to see what sorting algorithm it uses. Looks like it is 'mergesort’
Check it out. https://en.wikipedia.org/wiki/Merge_sort

1 Like

Thanks! I appreciate the explanation!