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.

program SortingByFunctions;

uses
  SysUtils, Generics.Collections, Generics.Defaults;

type
  TPerson = record
    Name: string;
    Age: Integer;
  end;

function CompareStringLength(const Left, Right: string): Integer;
begin
  Result := Length(Left) - Length(Right);
end;

function ComparePersonAge(const Left, Right: TPerson): Integer;
begin
  Result := Left.Age - Right.Age;
end;

var
  Fruits: TArray<string>;
  People: TArray<TPerson>;
  I: Integer;

begin
  Fruits := TArray<string>.Create('peach', 'banana', 'kiwi');

  // Sort fruits by string length
  TArray.Sort<string>(Fruits, TComparer<string>.Construct(CompareStringLength));
  
  WriteLn('Sorted fruits by length:');
  for I := 0 to High(Fruits) do
    Write(Fruits[I], ' ');
  WriteLn;

  // Create and sort people by age
  SetLength(People, 3);
  People[0] := TPerson.Create('Jax', 37);
  People[1] := TPerson.Create('TJ', 25);
  People[2] := TPerson.Create('Alex', 72);

  TArray.Sort<TPerson>(People, TComparer<TPerson>.Construct(ComparePersonAge));

  WriteLn('Sorted people by age:');
  for I := 0 to High(People) do
    WriteLn(People[I].Name, ' (', People[I].Age, ')');
end.

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:

Sorted fruits by length:
kiwi peach banana
Sorted people by age:
TJ (25)
Jax (37)
Alex (72)

This example demonstrates how to implement custom sorting logic in Pascal, allowing you to sort collections based on arbitrary criteria.