Sorting By Functions in Julia
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Julia.
In Julia, we use the sort!
function from the Sort
module to perform in-place sorting. The !
at the end of the function name is a Julia convention indicating that the function modifies its input.
For sorting strings by length, we define a comparison function lenCmp
that compares the lengths of two strings. We then pass this function to sort!
using the lt
(less than) keyword argument.
For sorting custom types like Person
, we use the by
keyword argument to specify a function that extracts the sorting key (in this case, the age
field) from each element.
Julia’s sorting functions are flexible and allow for easy customization of sorting behavior. The sort!
function modifies the input array in-place, which is efficient for large collections.
When you run this program, you should see output similar to:
This demonstrates how to implement custom sorting in Julia for both built-in types and user-defined structures.