How sort(function(a, b) { return a - b; }); Works Anyone?

Hello everyone,

Can someone help me understand how the .sort() method works on, for example, an array?

For example,
if I have array = [1, 5, 3, 10, 2, 7, 4], and I want to use array.sort((a, b) => a - b)), does my sort on the array keep running until there is no more a and b comparisons that return -1 or 1? Like, does it sort by comparing (1, 5) then (5, 3), sort, then (5, 10), then (10, 2)…and when done sorting through the array once (by starting my comparing at index 0 through the end of array) will result my array to be now [1, 3, 5, 2, 7, 4, 10]. As we can see, it’s still not sorted, so does my sort method work through my array again, and again, until there is no more sorting left to do?

Then what kind of sort is Javascrip’s .sort((a, b) => a - b))?

Also does anyone know a good youtube tutorial on how this sort with the callback function works?

1 Like

When you call sort it uses your callback function and passes in two numbers, and as you said if it returns 1 (positive value) it swaps the two numbers, then moves to the next numbers:

let arr = [2,1,3] // let's say that this is our array which we call .sort() on
// it takes the first two numbers (2,1) and calls your function like: callback(arr[i], arr[i+1]) I'll explain later why callback and arr[i] and arr[i+1]
[1,2,3] // since 2 - 1 is a positive value it swaps them (swapped example)
// then it moves onto (2,3), since 2-3 is a negative value it leaves it be
[1,2,3] // then I assume it loops through it once more to check if it is done

So why param(arr[i],arr[i+1)
That’s because it calls the callback like:

function sort(callback) {
  callback(arr[i],arr[i+1]);
}

You can even try making a function with a function as a parameter
And arr[i] and arr[i+1] because it loops through the array as long as it isn’t sorted
I assume it maybe looks something like this:

let sorted = false;
while (!sorted) {
  for (let i=0, neededSort = false;i<arr.length;i++) {
    if (callback(arr[i],arr[i+1] >= 1)) { // positive value
       // change the order
       neededSort = true;
    } else if (i + 1 === arr.length && !neededSort) {
       sorted = true;
    }
  }
}

I added neededSort to check if it sorted it (if it haven’t and it is the last value in array, then it means that it has been sorted)
You could check wikipedia and read it.
But what I would like you to watch is the bubble sort gif on the wiki page I just shared
I hope this helps :grinning:
If it doesn’t then just reply and I’ll try to clarify the problem :smiley:

Thank you so much! It makes sense now!

1 Like

Awesome Bubble sort GIF!!! That’s it in a nutshell and it makes it clear why it can be a slow-ish sorting algorithm esp. if you had a massive array.

This VisuAlgo has a nice visual rep of a sort too: https://visualgo.net/bn/sorting

1 Like