Within that article, “some ordering criterion” is mentioned. But what are they talking about? What “ordering criterion”? Sure it works, but I’ve never been satisfied with these black box explanations. If you happen to be one who is, then stop reading now.
Let’s consider a simple descending numerical array that we want to convert into an ascending one.
Pretty straightforward. But hang on. The sort() method also accepts an optional parameter in the form of a function. This can be quite useful in cases where, say, you want to alphabetically sort a list of songs but want to ignore any articles such as ‘The’ that the title may contain. A little more coding would be required, but I will stick to the simple numbered array example to illustrate further. The following code will do the exact same thing.
What are a & b? Why does it return a 1 and -1? Where does it return them to? ?
The values a & b are any two elements within the array. I use the word ‘any’ intentionally because sort() will loop through the array and compare these two values. In doing so, there will only be 3 possible outcomes: 1. a > b, 2. a < b, and 3. a = b. Depending on the criteria you use, case 1 may return the value 1 and case 2 return the value -1. Case 3 will obviously do nothing.
The magnitude of the returned numbers is not important, only whether they are positive or negative. You can use ‘return +27’ and ‘return -14’ and it will still work. But return that value to where? It is delivered back to the sort() method because it needs that information to determine if the order of the two compared values are to be changed or not.
Let’s now have a look at how two different browsers handle their respective sorting algorithms. The numbers in red are the a & b values that the algorithm will compare. You will notice that in Chrome, the values simply switch their positions, whereas in Firefox, a single value is moved in front of the one it is being compared to.
The Firefox algorithm seems more efficient as it is saving us 3 sorting steps in this example. But as already mentioned, the sort() method doesn’t care. It can go home happy knowing it’s sorted everything out.