Sorting By Functions in D Programming Language
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 D.
In this D code:
We import necessary modules:
std.stdio
for output,std.algorithm
for sorting, andstd.array
for array operations.We define a
lenCmp
function that compares strings based on their length.We use
sort!(lenCmp)
to sort thefruits
array using our custom comparison function. The!
syntax is D’s way of passing a template argument.For sorting custom types, we define a
Person
struct.We sort the
people
array using an inline lambda function that comparesPerson
objects based on their age.
Note: In D, we don’t need to explicitly implement a Compare
function that returns -1, 0, or 1. Instead, we use boolean comparison functions or lambdas that return true if the first argument should be sorted before the second.
When you run this program, you should see output similar to:
This demonstrates how to perform custom sorting in D, both for built-in types like strings and for user-defined types like structs.