You may have expected the Java code to be messy and verbose with iterators and complex comparison functions. With Java 8 it is short and concise thanks to streams and the comparator API. Also using the short-hand lambda syntax (method reference) I was able to write
Person::getLast instead of
(p) -> p.getLast(). Most of the code in the full example is for creating the Person POJO.
sort() and it uses the callback when making comparisons.
One thing that was strange when executing this code is that both
console.info() invocations produced the sorted array even though the first
console.info() occurs before people is sorted. This is because console functions are asynchronous in some environments. Therefore we may not get the results at the time we expect. You can't always trust
I really like the Swift implementation for sorting. In general I prefer using classes over structs in Swift (just a personal preference!), but in a simple case like this one a struct makes perfect sense.
If you don't know much Swift the sorting operation may look a bit confusing. The
sort() function takes a closure you can use parameter shorthands which are represented as
$1 being the first parameter,
$2 being the second, etc.)1. I also utilized trailing closure syntax which can be used when the closure is the last parameter of a function. Trailing closure syntax enables the removal of a function invocations parenthesis, and you can see
sort() uses no parenthesis2! All these tricks are fun to look into and allow for very concise Swift code.
The PHP solution may be my least favorite. I created the
People object and an array of
uasort() is used for user defined comparisons where argument one is the array and argument two is the string name of the comparison function. Why can't I treat the comparison function as a first class citizen and pass it as the second
uasort() argument? This code feels ugly.
As you probably guessed, the winner for most concise comparison sort goes to Python. Thanks to optional arguments, the
sort() function is really sleek!
As you also likely guessed, the C code is by far the most involved. The structs do make the sorting easier (I originally tried sorting lists of lists of lists, but the pointers got out of control and I couldn't figure it out!). I utilized the standard libraries
qsort() function and passed in a comparison function3.