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.

using Sort

function main()
    fruits = ["peach", "banana", "kiwi"]

    # We implement a comparison function for string lengths
    lenCmp = (a, b) -> cmp(length(a), length(b))

    # Now we can call sort! with this custom comparison function to sort fruits by name length
    sort!(fruits, lt=lenCmp)
    println(fruits)

    # We can use the same technique to sort an array of values that aren't built-in types
    struct Person
        name::String
        age::Int
    end

    people = [
        Person("Jax", 37),
        Person("TJ", 25),
        Person("Alex", 72)
    ]

    # Sort people by age using sort!
    #
    # Note: if the Person struct is large,
    # you may want the array to contain Ref{Person} instead
    # and adjust the sorting function accordingly. If in
    # doubt, benchmark!
    sort!(people, by=p -> p.age)
    println(people)
end

main()

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:

["kiwi", "peach", "banana"]
[Person("TJ", 25), Person("Jax", 37), Person("Alex", 72)]

This demonstrates how to implement custom sorting in Julia for both built-in types and user-defined structures.