Sorting in Pascal

Our sorting example demonstrates how to sort different types of data in Pascal. We’ll look at sorting for built-in types first.

program Sorting;

uses
  SysUtils;

type
  TStringArray = array of string;
  TIntegerArray = array of Integer;

procedure SortStrings(var arr: TStringArray);
var
  i, j: Integer;
  temp: string;
begin
  for i := Low(arr) to High(arr) - 1 do
    for j := i + 1 to High(arr) do
      if arr[i] > arr[j] then
      begin
        temp := arr[i];
        arr[i] := arr[j];
        arr[j] := temp;
      end;
end;

procedure SortIntegers(var arr: TIntegerArray);
var
  i, j: Integer;
  temp: Integer;
begin
  for i := Low(arr) to High(arr) - 1 do
    for j := i + 1 to High(arr) do
      if arr[i] > arr[j] then
      begin
        temp := arr[i];
        arr[i] := arr[j];
        arr[j] := temp;
      end;
end;

function IsSorted(const arr: TIntegerArray): Boolean;
var
  i: Integer;
begin
  Result := True;
  for i := Low(arr) to High(arr) - 1 do
    if arr[i] > arr[i + 1] then
    begin
      Result := False;
      Exit;
    end;
end;

var
  strs: TStringArray;
  ints: TIntegerArray;
  s: Boolean;

begin
  // Sorting functions work for different types.
  // Here's an example with strings:
  SetLength(strs, 3);
  strs[0] := 'c';
  strs[1] := 'a';
  strs[2] := 'b';
  SortStrings(strs);
  WriteLn('Strings: ', string(strs[0]), ' ', string(strs[1]), ' ', string(strs[2]));

  // An example of sorting integers:
  SetLength(ints, 3);
  ints[0] := 7;
  ints[1] := 2;
  ints[2] := 4;
  SortIntegers(ints);
  WriteLn('Ints:    ', ints[0], ' ', ints[1], ' ', ints[2]);

  // We can also check if an array is already in sorted order.
  s := IsSorted(ints);
  WriteLn('Sorted:  ', s);
end.

To run the program, save it as sorting.pas and use a Pascal compiler like Free Pascal:

$ fpc sorting.pas
$ ./sorting
Strings: a b c
Ints:    2 4 7
Sorted:  TRUE

In this Pascal example, we’ve implemented our own sorting functions for strings and integers, as Pascal doesn’t have a built-in generic sorting function like Go’s slices.Sort. We’ve also created an IsSorted function to check if an integer array is in sorted order.

The structure of the program is similar to the original, but adapted to Pascal’s syntax and conventions. We use procedures to sort the arrays in-place, and a function to check if an array is sorted.

Note that Pascal uses 1-based indexing by default, but we’ve used Low(arr) and High(arr) to make the code more flexible and to mimic the 0-based indexing of the original Go code.