Sorting (placing a collection of items in order) is one of the most common operations in information processing. Arrays are the most common data structure that holds objects we want to sort (collections). So naturally, most modern programming languages provide built-in sort methods to sort arrays. And they are usually very easy and intuitive to use.
In Python for example,
will print out the sorted array [1,9,21,100]
In Swift, the code can be even a bit "cute" with emojis!
will printout [ 1, 100, 21, 9 ]
A big oops
- It must have two parameters (say a and b)
- It must return a value that is either less than 0, or greater than 0 or equal to 0
- It must always return the same value when given a specific pair of elements a and b as its two argument
The override behavior
TL;DR: i.e. the code
Therefore by the override behavior described above a will be indexed lower than b if a < b, a will be indexed higher than b if a > b. Thus the sort will work for numbers.
Here is an excellent MDN article explaining the details.
Because we are dealing with numbers, returning the value of a-b has the same effect as spelling out the three cases a > b, a < b and a == b as we have done above. We can make our compare function anonymous and use the a-b pattern to make it a bit more compact like the following:
The good that comes out of this "pain"
OK, that is a lot to go through to sort a few numbers. We agree! But once you get used to the pattern it will become second nature. Being able to provide a customized compare function to override sort is a very powerful programming tool. We will see one example of it in action in this blog.