Sorting By Functions in Pascal
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 Pascal.
In this Pascal example, we demonstrate custom sorting using the TArray.Sort
method from the Generics.Collections
unit. We implement two comparison functions: one for sorting strings by length and another for sorting people by age.
We first sort the Fruits
array using a custom comparison function CompareStringLength
. This function compares the lengths of two strings, allowing us to sort the fruits by their name length.
Next, we define a TPerson
record type with Name
and Age
fields. We create an array of TPerson
and sort it using the ComparePersonAge
function, which compares the ages of two people.
The TComparer<T>.Construct
method is used to create a comparison object from our custom comparison functions. This allows us to pass these custom sorting criteria to the TArray.Sort
method.
When you run this program, it will output:
This example demonstrates how to implement custom sorting logic in Pascal, allowing you to sort collections based on arbitrary criteria.