ZetCode

Sorting in Pascal

last modified November 18, 2026 Free Pascal 3.2.2

Sorting puts the elements of a collection in order. Pascal programs can use the library sorts in TStringList and TList<T>, or write one of the classic algorithms. This article implements bubble, selection, insertion, quick, and merge sort on an array of integers, then shows the two library sorts and compares their behaviour. The examples use the same nine values so that the results are easy to compare.

Bubble sort

Bubble sort compares adjacent pairs and swaps them when they are out of order. After one pass the largest value has moved to the end, so the next pass can stop one position earlier. If a pass makes no swaps, the array is already sorted and the loop can stop early.

bubble.pas
program bubble;
{$mode objfpc}{$H+}

type
  TIntArray = array of Integer;

procedure PrintArray(const A: TIntArray);
var
  I: Integer;
begin
  for I := Low(A) to High(A) do
  begin
    if I > Low(A) then
      Write(' ');
    Write(A[I]);
  end;
  WriteLn;
end;

procedure BubbleSort(var A: TIntArray);
var
  I, J, Temp: Integer;
  Swapped: Boolean;
begin
  for I := High(A) downto 1 do
  begin
    Swapped := False;
    for J := 0 to I - 1 do
      if A[J] > A[J + 1] then
      begin
        Temp := A[J];
        A[J] := A[J + 1];
        A[J + 1] := Temp;
        Swapped := True;
      end;
    if not Swapped then
      Break;
  end;
end;

var
  Data: TIntArray;

begin
  Data := [5, 2, 9, 1, 7, 3, 8, 6, 4];
  Write('before: '); PrintArray(Data);
  BubbleSort(Data);
  Write('after:  '); PrintArray(Data);
end.

The early exit makes bubble sort fast on an array that is already sorted, but the worst case is still quadratic: about n2/2 comparisons for n elements. The algorithm is stable, because equal values are never swapped, and it sorts in place with one temporary variable.

$ fpc -gl bubble.pas
$ ./bubble
before: 5 2 9 1 7 3 8 6 4
after:  1 2 3 4 5 6 7 8 9

Selection sort

Selection sort finds the smallest remaining element and swaps it into the next position. After i passes the first i elements are in their final order. Unlike bubble sort, it performs at most one swap per pass, which matters when moving an element is expensive.

selection.pas
program selection;
{$mode objfpc}{$H+}

type
  TIntArray = array of Integer;

procedure PrintArray(const A: TIntArray);
var
  I: Integer;
begin
  for I := Low(A) to High(A) do
  begin
    if I > Low(A) then
      Write(' ');
    Write(A[I]);
  end;
  WriteLn;
end;

procedure SelectionSort(var A: TIntArray);
var
  I, J, MinIndex, Temp: Integer;
begin
  for I := 0 to High(A) - 1 do
  begin
    MinIndex := I;
    for J := I + 1 to High(A) do
      if A[J] < A[MinIndex] then
        MinIndex := J;
    if MinIndex <> I then
    begin
      Temp := A[I];
      A[I] := A[MinIndex];
      A[MinIndex] := Temp;
    end;
  end;
end;

var
  Data: TIntArray;

begin
  Data := [5, 2, 9, 1, 7, 3, 8, 6, 4];
  Write('before: '); PrintArray(Data);
  SelectionSort(Data);
  Write('after:  '); PrintArray(Data);
end.

Selection sort always performs the same number of comparisons, so it does not benefit from an already sorted input. It is not stable: swapping the minimum into place can move an equal element past another one. The advantage is the small number of writes, which is why it appears in systems with expensive memory writes.

$ fpc -gl selection.pas
$ ./selection
before: 5 2 9 1 7 3 8 6 4
after:  1 2 3 4 5 6 7 8 9

Insertion sort

Insertion sort grows a sorted prefix. It takes the next element, shifts the larger elements of the prefix one position to the right, and inserts the element into the gap. The shifting loop stops as soon as the previous element is not larger, which makes the algorithm linear on data that is already sorted or nearly sorted.

insertion.pas
program insertion;
{$mode objfpc}{$H+}

type
  TIntArray = array of Integer;

procedure PrintArray(const A: TIntArray);
var
  I: Integer;
begin
  for I := Low(A) to High(A) do
  begin
    if I > Low(A) then
      Write(' ');
    Write(A[I]);
  end;
  WriteLn;
end;

procedure InsertionSort(var A: TIntArray);
var
  I, J, Key: Integer;
begin
  for I := 1 to High(A) do
  begin
    Key := A[I];
    J := I - 1;
    while (J >= 0) and (A[J] > Key) do
    begin
      A[J + 1] := A[J];
      Dec(J);
    end;
    A[J + 1] := Key;
  end;
end;

var
  Data: TIntArray;

begin
  Data := [5, 2, 9, 1, 7, 3, 8, 6, 4];
  Write('before: '); PrintArray(Data);
  InsertionSort(Data);
  Write('after:  '); PrintArray(Data);
end.

Insertion sort is stable and in-place, and it is usually the fastest of the three quadratic algorithms on small arrays. Many library sorts switch to insertion sort for short subarrays, where its low overhead beats the recursive machinery of quick or merge sort. The worst case is still quadratic when the input is in reverse order.

$ fpc -gl insertion.pas
$ ./insertion
before: 5 2 9 1 7 3 8 6 4
after:  1 2 3 4 5 6 7 8 9

Quick sort

Quick sort chooses a pivot, partitions the array so that smaller elements are on the left and larger elements on the right, and then sorts both parts recursively. The version below uses the middle element as the pivot and the Hoare partition scheme with two indices that move toward each other.

quicksort.pas
program quicksort;
{$mode objfpc}{$H+}

type
  TIntArray = array of Integer;

procedure PrintArray(const A: TIntArray);
var
  I: Integer;
begin
  for I := Low(A) to High(A) do
  begin
    if I > Low(A) then
      Write(' ');
    Write(A[I]);
  end;
  WriteLn;
end;

procedure QuickSort(var A: TIntArray; Low, High: Integer);
var
  Pivot, I, J, Temp: Integer;
begin
  if Low >= High then
    Exit;
  Pivot := A[(Low + High) div 2];
  I := Low;
  J := High;
  repeat
    while A[I] < Pivot do Inc(I);
    while A[J] > Pivot do Dec(J);
    if I <= J then
    begin
      Temp := A[I];
      A[I] := A[J];
      A[J] := Temp;
      Inc(I);
      Dec(J);
    end;
  until I > J;
  QuickSort(A, Low, J);
  QuickSort(A, I, High);
end;

var
  Data: TIntArray;

begin
  Data := [5, 2, 9, 1, 7, 3, 8, 6, 4];
  Write('before: '); PrintArray(Data);
  QuickSort(Data, Low(Data), High(Data));
  Write('after:  '); PrintArray(Data);
end.

The pivot value stays in the array, and the two indices stop on elements that are on the wrong side. Swapping them and moving inward partitions the array in place. Quick sort averages n log n comparisons but degrades to quadratic time when the pivot is consistently extreme, which can happen with a bad pivot choice or adversarial input.

$ fpc -gl quicksort.pas
$ ./quicksort
before: 5 2 9 1 7 3 8 6 4
after:  1 2 3 4 5 6 7 8 9

Merge sort

Merge sort splits the array in half, sorts each half recursively, and merges the two sorted halves into a temporary array. The merge compares the front elements and copies the smaller one; when one half is exhausted, the rest of the other half is copied. The result is then written back into the original array.

merge.pas
program merge;
{$mode objfpc}{$H+}

type
  TIntArray = array of Integer;

procedure PrintArray(const A: TIntArray);
var
  I: Integer;
begin
  for I := Low(A) to High(A) do
  begin
    if I > Low(A) then
      Write(' ');
    Write(A[I]);
  end;
  WriteLn;
end;

procedure Merge(var A, Temp: TIntArray; Low, Mid, High: Integer);
var
  I, J, K: Integer;
begin
  I := Low;
  J := Mid + 1;
  K := Low;
  while (I <= Mid) and (J <= High) do
  begin
    if A[I] <= A[J] then
    begin
      Temp[K] := A[I];
      Inc(I);
    end
    else
    begin
      Temp[K] := A[J];
      Inc(J);
    end;
    Inc(K);
  end;
  while I <= Mid do
  begin
    Temp[K] := A[I];
    Inc(I); Inc(K);
  end;
  while J <= High do
  begin
    Temp[K] := A[J];
    Inc(J); Inc(K);
  end;
  for K := Low to High do
    A[K] := Temp[K];
end;

procedure MergeSort(var A, Temp: TIntArray; Low, High: Integer);
var
  Mid: Integer;
begin
  if Low >= High then
    Exit;
  Mid := (Low + High) div 2;
  MergeSort(A, Temp, Low, Mid);
  MergeSort(A, Temp, Mid + 1, High);
  Merge(A, Temp, Low, Mid, High);
end;

var
  Data, Temp: TIntArray;

begin
  Data := [5, 2, 9, 1, 7, 3, 8, 6, 4];
  SetLength(Temp, Length(Data));
  Write('before: '); PrintArray(Data);
  MergeSort(Data, Temp, Low(Data), High(Data));
  Write('after:  '); PrintArray(Data);
end.

The temporary array is allocated once, before the recursion starts, and reused by every merge. Merge sort guarantees n log n comparisons in all cases and is stable because the comparison takes from the left half when the values are equal. The cost is the extra array, which is why in-place sorts are preferred when memory is tight.

$ fpc -gl merge.pas
$ ./merge
before: 5 2 9 1 7 3 8 6 4
after:  1 2 3 4 5 6 7 8 9

Sorting a TStringList

TStringList.Sort sorts the strings in place. By default the comparison ignores case, so alice sorts before Bob even though the lowercase letter has a larger byte value. The CaseSensitive property changes that, and a custom OnCompare handler can define any other order.

listsort.pas
program listsort;
{$mode objfpc}{$H+}

uses Classes, SysUtils;

var
  Names: TStringList;
  I: Integer;

begin
  Names := TStringList.Create;
  try
    Names.Add('Caroline');
    Names.Add('alice');
    Names.Add('Bob');
    Names.Add('dave');
    Names.Sort;
    for I := 0 to Names.Count - 1 do
      WriteLn(I, ': ', Names[I]);
  finally
    Names.Free;
  end;
end.

The sorted order is alice, Bob, Caroline, dave. The list owns its strings, so freeing the list releases them; the try..finally block guarantees that even if the sort raises an exception. A list that is kept sorted can also be searched with Find, which the searching article covers.

$ fpc -gl listsort.pas
$ ./listsort
0: alice
1: Bob
2: Caroline
3: dave

Sorting a generic list

TList<T>.Sort uses the default comparer for the element type when it is called without arguments. A custom comparer is a function that returns a negative number when the first argument sorts first, zero when they are equal, and a positive number when the second sorts first. In ObjFPC mode the comparer type must be specialized, and its parameters are declared constref.

genlistsort.pas
program genlistsort;
{$mode objfpc}{$H+}

uses SysUtils, Generics.Collections, Generics.Defaults;

type
  TIntList = specialize TList<Integer>;

function Descending(constref A, B: Integer): Integer;
begin
  Result := B - A;
end;

var
  Numbers: TIntList;
  I: Integer;

begin
  Numbers := TIntList.Create;
  try
    Numbers.Add(30);
    Numbers.Add(10);
    Numbers.Add(50);
    Numbers.Add(20);
    Numbers.Add(40);
    Numbers.Sort;
    Write('ascending:  ');
    for I := 0 to Numbers.Count - 1 do
    begin
      if I > 0 then
        Write(' ');
      Write(Numbers[I]);
    end;
    WriteLn;
    Numbers.Sort(specialize TComparer<Integer>.Construct(@Descending));
    Write('descending: ');
    for I := 0 to Numbers.Count - 1 do
    begin
      if I > 0 then
        Write(' ');
      Write(Numbers[I]);
    end;
    WriteLn;
  finally
    Numbers.Free;
  end;
end.

The first sort uses the default ascending order. The second passes a comparer built from Descending, so the largest value is considered smaller. The same pattern works for records and classes: write a function that compares two values by the field that defines the order.

$ fpc -gl genlistsort.pas
$ ./genlistsort
ascending:  10 20 30 40 50
descending: 50 40 30 20 10

Stability and complexity

A sort is stable when equal elements keep their original relative order. Merge sort and insertion sort are stable; selection sort and quicksort are not. Stability matters when a list is sorted by one field after being sorted by another, or when the original order carries meaning that the sort key does not capture.

Bubble, selection, and insertion sort are quadratic in the worst case, quick sort is n log n on average and quadratic in the worst case, and merge sort is n log n in every case but needs linear extra memory. For small arrays the quadratic algorithms are often fast enough and have little overhead; for large data, use the library sort or a guaranteed n log n algorithm.

Next steps

The searching article uses sorted arrays for binary search, and the hash tables article compares that with hashed lookup. The recursion article explains the calls behind quick sort and merge sort, and the dynamic arrays article describes the array type that these procedures modify in place.

Source

Free Pascal Reference guide

Free Pascal TStringList

Sorting algorithm on Wikipedia

In this article we have implemented bubble, selection, insertion, quick, and merge sort, sorted a string list and a generic list, supplied a custom comparer, and compared stability and complexity. The series continues with searching in Pascal.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.