Modula-2 sorting
last modified November 27, 2026 Modula-2
Sorting puts the elements of an array into order. This article writes three classic algorithms on open arrays of integers: insertion sort, quicksort and merge sort. It then collects them in a module whose procedures take a comparator, a procedure that decides which of two elements comes first, and uses the module to count comparisons and to sort records.
The procedure types article
introduced comparators with an insertion sort. Quicksort and merge sort are
recursive; the recursion article covers
the technique. All examples are compiled with -fiso.
Insertion sort
Insertion sort builds the sorted array from left to right. It takes the next element and moves it left past every larger element, the way cards are sorted in a hand.
MODULE insertion;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
data: ARRAY [0..9] OF INTEGER;
PROCEDURE Sort(VAR a: ARRAY OF INTEGER);
VAR
i, j: CARDINAL;
key: INTEGER;
BEGIN
FOR i := 1 TO HIGH(a) DO
key := a[i];
j := i;
WHILE (j > 0) AND (a[j - 1] > key) DO
a[j] := a[j - 1];
DEC(j)
END;
a[j] := key
END
END Sort;
PROCEDURE Show(label: ARRAY OF CHAR; VAR a: ARRAY OF INTEGER);
VAR
i: CARDINAL;
BEGIN
WriteString(label);
FOR i := 0 TO HIGH(a) DO
WriteInt(a[i], 4)
END;
WriteLn
END Show;
BEGIN
data[0] := 31; data[1] := 7; data[2] := 52; data[3] := -4; data[4] := 18;
data[5] := 7; data[6] := 90; data[7] := 0; data[8] := 25; data[9] := 3;
Show("before:", data);
Sort(data);
Show("after: ", data)
END insertion.
Before step i, the elements a[0] to
a[i - 1] are sorted. The element a[i] is saved in
key, the larger elements to its left move one place right, and
key goes into the gap. The test j > 0 comes
first, so a[j - 1] is never read with j equal to
0: AND does not evaluate its right operand when the left one is
false. The array is an open array parameter, so Sort works on
arrays of any length.
$ gm2 -fiso insertion.mod -o insertion $ ./insertion before: 31 7 52 -4 18 7 90 0 25 3 after: -4 0 3 7 7 18 25 31 52 90
Test data in a module
Every sort needs data to work on, a way to show it and a check that the
result is in order. These helpers go into a Samples module, so
that the later programs show only the sort.
DEFINITION MODULE Samples; PROCEDURE Fill(VAR a: ARRAY OF INTEGER; seed: CARDINAL); PROCEDURE Show(label: ARRAY OF CHAR; VAR a: ARRAY OF INTEGER); PROCEDURE IsSorted(VAR a: ARRAY OF INTEGER): BOOLEAN; END Samples.
The definition module exports three procedures. The arrays are
VAR parameters, so large arrays are not copied.
IMPLEMENTATION MODULE Samples;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
PROCEDURE Fill(VAR a: ARRAY OF INTEGER; seed: CARDINAL);
VAR
i: CARDINAL;
BEGIN
FOR i := 0 TO HIGH(a) DO
seed := (seed * 75 + 74) MOD 65537;
a[i] := INTEGER(seed MOD 1000)
END
END Fill;
PROCEDURE Show(label: ARRAY OF CHAR; VAR a: ARRAY OF INTEGER);
VAR
i: CARDINAL;
BEGIN
WriteString(label);
FOR i := 0 TO HIGH(a) DO
WriteInt(a[i], 4)
END;
WriteLn
END Show;
PROCEDURE IsSorted(VAR a: ARRAY OF INTEGER): BOOLEAN;
VAR
i: CARDINAL;
BEGIN
FOR i := 1 TO HIGH(a) DO
IF a[i - 1] > a[i] THEN
RETURN FALSE
END
END;
RETURN TRUE
END IsSorted;
END Samples.
Fill produces pseudo-random numbers from 0 to 999 with a
linear congruential generator: each new seed is computed from
the previous one. The same seed always gives the same numbers, so the runs
can be repeated. IsSorted checks that no element is larger than
the next one.
MODULE checked;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Samples IMPORT Fill, Show, IsSorted;
VAR
small: ARRAY [0..11] OF INTEGER;
large: ARRAY [0..4999] OF INTEGER;
PROCEDURE Sort(VAR a: ARRAY OF INTEGER);
VAR
i, j: CARDINAL;
key: INTEGER;
BEGIN
FOR i := 1 TO HIGH(a) DO
key := a[i];
j := i;
WHILE (j > 0) AND (a[j - 1] > key) DO
a[j] := a[j - 1];
DEC(j)
END;
a[j] := key
END
END Sort;
BEGIN
Fill(small, 1);
Show("before:", small);
Sort(small);
Show("after: ", small);
Fill(large, 2);
Sort(large);
IF IsSorted(large) THEN
WriteString("5000 numbers sorted")
ELSE
WriteString("5000 numbers NOT sorted")
END;
WriteLn
END checked.
The program sorts twelve numbers, which can be checked by eye, and five
thousand numbers, which are checked by IsSorted.
Samples is compiled once and linked to every program of the
article.
$ gm2 -fiso -c Samples.mod $ gm2 -fiso checked.mod Samples.o -o checked $ ./checked before: 149 249 305 44 283 819 463 689 472 901 742 836 after: 44 149 249 283 305 463 472 689 742 819 836 901 5000 numbers sorted
Quicksort
Quicksort picks one element, the pivot, and partitions the array: smaller elements go to the left part, larger ones to the right part. The two parts are then sorted recursively. The version below follows Wirth's Algorithms and Data Structures.
MODULE quick;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Samples IMPORT Fill, Show, IsSorted;
VAR
small: ARRAY [0..11] OF INTEGER;
large: ARRAY [0..99999] OF INTEGER;
PROCEDURE QuickSort(VAR a: ARRAY OF INTEGER; lo, hi: INTEGER);
VAR
i, j, pivot, t: INTEGER;
BEGIN
i := lo; j := hi;
pivot := a[(lo + hi) DIV 2];
REPEAT
WHILE a[i] < pivot DO INC(i) END;
WHILE a[j] > pivot DO DEC(j) END;
IF i <= j THEN
t := a[i]; a[i] := a[j]; a[j] := t;
INC(i); DEC(j)
END
UNTIL i > j;
IF lo < j THEN QuickSort(a, lo, j) END;
IF i < hi THEN QuickSort(a, i, hi) END
END QuickSort;
PROCEDURE Sort(VAR a: ARRAY OF INTEGER);
BEGIN
QuickSort(a, 0, HIGH(a))
END Sort;
BEGIN
Fill(small, 1);
Show("before:", small);
Sort(small);
Show("after: ", small);
Fill(large, 2);
Sort(large);
IF IsSorted(large) THEN
WriteString("100000 numbers sorted")
ELSE
WriteString("100000 numbers NOT sorted")
END;
WriteLn
END quick.
The pivot is the middle element. i moves right past elements
smaller than the pivot and j moves left past larger ones; when
both stop, the two elements are swapped. When the indexes cross, everything
from lo to j is not larger than the pivot and
everything from i to hi is not smaller, and the
two parts are sorted by recursive calls. The indexes are
INTEGER, because j can go below 0, which a
CARDINAL cannot hold. Sort hides the bounds from
the caller. Quicksort handles one hundred thousand numbers without
trouble; insertion sort would need several seconds for them.
$ gm2 -fiso quick.mod Samples.o -o quick $ ./quick before: 149 249 305 44 283 819 463 689 472 901 742 836 after: 44 149 249 283 305 463 472 689 742 819 836 901 100000 numbers sorted
Merge sort
Merge sort splits the array into two halves, sorts each half recursively, and merges the two sorted halves into one. Merging needs a second array of the same size.
MODULE merge;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Samples IMPORT Fill, Show, IsSorted;
VAR
small, smallTmp: ARRAY [0..11] OF INTEGER;
large, largeTmp: ARRAY [0..99999] OF INTEGER;
PROCEDURE Merge(VAR a, tmp: ARRAY OF INTEGER; lo, mid, hi: CARDINAL);
VAR
i, j, k: CARDINAL;
BEGIN
i := lo; j := mid + 1;
FOR k := lo TO hi DO
IF (j > hi) OR (i <= mid) AND (a[i] <= a[j]) THEN
tmp[k] := a[i]; INC(i)
ELSE
tmp[k] := a[j]; INC(j)
END
END;
FOR k := lo TO hi DO
a[k] := tmp[k]
END
END Merge;
PROCEDURE MergeSort(VAR a, tmp: ARRAY OF INTEGER; lo, hi: CARDINAL);
VAR
mid: CARDINAL;
BEGIN
IF lo < hi THEN
mid := (lo + hi) DIV 2;
MergeSort(a, tmp, lo, mid);
MergeSort(a, tmp, mid + 1, hi);
Merge(a, tmp, lo, mid, hi)
END
END MergeSort;
BEGIN
Fill(small, 1);
Show("before:", small);
MergeSort(small, smallTmp, 0, HIGH(small));
Show("after: ", small);
Fill(large, 2);
MergeSort(large, largeTmp, 0, HIGH(large));
IF IsSorted(large) THEN
WriteString("100000 numbers sorted")
ELSE
WriteString("100000 numbers NOT sorted")
END;
WriteLn
END merge.
Merge takes the smaller of the front elements of the two
halves into tmp until both halves are used up, and copies the
result back. An element is taken from the left half when the right half is
used up, or when the left half still has elements and its front element is
not larger. AND binds more tightly than OR, and
both stop as soon as the result is known, so a[j] is not read
after the right half ends. The second array is passed by the caller, because
Modula-2 cannot declare a local array of the size of an open array.
$ gm2 -fiso merge.mod Samples.o -o merge $ ./merge before: 149 249 305 44 283 819 463 689 472 901 742 836 after: 44 149 249 283 305 463 472 689 742 819 836 901 100000 numbers sorted
A sorting module
The three sorts go into a Sorts module. Each takes a
comparator of the procedure type Before instead of using
<, so the caller decides the order.
DEFINITION MODULE Sorts; TYPE Before = PROCEDURE (INTEGER, INTEGER): BOOLEAN; PROCEDURE InsertionSort(VAR a: ARRAY OF INTEGER; before: Before); PROCEDURE QuickSort(VAR a: ARRAY OF INTEGER; before: Before); PROCEDURE MergeSort(VAR a, tmp: ARRAY OF INTEGER; before: Before); END Sorts.
before(x, y) must return TRUE when
x belongs before y, and FALSE for
equal elements.
IMPLEMENTATION MODULE Sorts;
PROCEDURE InsertionSort(VAR a: ARRAY OF INTEGER; before: Before);
VAR
i, j: CARDINAL;
key: INTEGER;
BEGIN
FOR i := 1 TO HIGH(a) DO
key := a[i]; j := i;
WHILE (j > 0) AND before(key, a[j - 1]) DO
a[j] := a[j - 1]; DEC(j)
END;
a[j] := key
END
END InsertionSort;
PROCEDURE Quick(VAR a: ARRAY OF INTEGER; lo, hi: INTEGER; before: Before);
VAR
i, j, pivot, t: INTEGER;
BEGIN
i := lo; j := hi;
pivot := a[(lo + hi) DIV 2];
REPEAT
WHILE before(a[i], pivot) DO INC(i) END;
WHILE before(pivot, a[j]) DO DEC(j) END;
IF i <= j THEN
t := a[i]; a[i] := a[j]; a[j] := t;
INC(i); DEC(j)
END
UNTIL i > j;
IF lo < j THEN Quick(a, lo, j, before) END;
IF i < hi THEN Quick(a, i, hi, before) END
END Quick;
PROCEDURE QuickSort(VAR a: ARRAY OF INTEGER; before: Before);
BEGIN
Quick(a, 0, HIGH(a), before)
END QuickSort;
PROCEDURE Merge(VAR a, tmp: ARRAY OF INTEGER; lo, hi: CARDINAL;
before: Before);
VAR
i, j, k, mid: CARDINAL;
BEGIN
IF lo < hi THEN
mid := (lo + hi) DIV 2;
Merge(a, tmp, lo, mid, before);
Merge(a, tmp, mid + 1, hi, before);
i := lo; j := mid + 1;
FOR k := lo TO hi DO
IF (j > hi) OR (i <= mid) AND NOT before(a[j], a[i]) THEN
tmp[k] := a[i]; INC(i)
ELSE
tmp[k] := a[j]; INC(j)
END
END;
FOR k := lo TO hi DO a[k] := tmp[k] END
END
END Merge;
PROCEDURE MergeSort(VAR a, tmp: ARRAY OF INTEGER; before: Before);
BEGIN
Merge(a, tmp, 0, HIGH(a), before)
END MergeSort;
END Sorts.
Every a < b of the previous sections is now
before(a, b). In the merge, the left element is taken unless
the right one belongs strictly before it, so equal elements keep their
order. Quick and Merge are not exported; the
module also folds the merging into the recursive procedure to stay
short.
MODULE orders;
FROM Samples IMPORT Fill, Show;
FROM Sorts IMPORT InsertionSort, QuickSort, MergeSort;
VAR
data, tmp: ARRAY [0..11] OF INTEGER;
PROCEDURE Ascending(a, b: INTEGER): BOOLEAN;
BEGIN
RETURN a < b
END Ascending;
PROCEDURE Descending(a, b: INTEGER): BOOLEAN;
BEGIN
RETURN a > b
END Descending;
PROCEDURE ByLastDigit(a, b: INTEGER): BOOLEAN;
BEGIN
RETURN a MOD 10 < b MOD 10
END ByLastDigit;
BEGIN
Fill(data, 1);
Show("data: ", data);
InsertionSort(data, Descending);
Show("insertion: ", data);
QuickSort(data, Ascending);
Show("quick: ", data);
MergeSort(data, tmp, ByLastDigit);
Show("merge: ", data)
END orders.
The program sorts the same data three times with different comparators.
ByLastDigit orders numbers by their last digit. Merge sort
keeps equal elements in their previous order: 472 and 742 both end in 2 and
stay in the ascending order the quicksort produced.
$ gm2 -fiso -c Sorts.mod $ gm2 -fiso orders.mod Samples.o Sorts.o -o orders $ ./orders data: 149 249 305 44 283 819 463 689 472 901 742 836 insertion: 901 836 819 742 689 472 463 305 283 249 149 44 quick: 44 149 249 283 305 463 472 689 742 819 836 901 merge: 901 472 742 283 463 44 305 836 149 249 689 819
Counting comparisons
A comparator can do more than compare. The next one counts how often it is called, which shows how much work each algorithm does on different kinds of input.
MODULE counting;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Samples IMPORT Fill;
FROM Sorts IMPORT InsertionSort, QuickSort, MergeSort;
CONST
N = 2000;
TYPE
Input = (random, sorted, reversed, equal);
VAR
data, tmp: ARRAY [0..N - 1] OF INTEGER;
count: CARDINAL;
input: Input;
PROCEDURE Less(a, b: INTEGER): BOOLEAN;
BEGIN
INC(count);
RETURN a < b
END Less;
PROCEDURE Prepare(kind: Input);
VAR
i: CARDINAL;
BEGIN
count := 0;
CASE kind OF
random: Fill(data, 7)
| sorted: FOR i := 0 TO N - 1 DO data[i] := i END
| reversed: FOR i := 0 TO N - 1 DO data[i] := N - i END
| equal: FOR i := 0 TO N - 1 DO data[i] := 5 END
END
END Prepare;
BEGIN
WriteString("input insertion quick merge"); WriteLn;
FOR input := random TO equal DO
CASE input OF
random: WriteString("random ")
| sorted: WriteString("sorted ")
| reversed: WriteString("reversed ")
| equal: WriteString("equal ")
END;
Prepare(input); InsertionSort(data, Less); WriteCard(count, 12);
Prepare(input); QuickSort(data, Less); WriteCard(count, 11);
Prepare(input); MergeSort(data, tmp, Less); WriteCard(count, 11);
WriteLn
END
END counting.
Less increments the global count on every call.
Prepare resets the counter and fills the array with two
thousand random, sorted, reversed or equal numbers. Insertion sort needs
about n2/4 comparisons on random data and
n2/2 on reversed data, but only n − 1 on data that
is already sorted. Quicksort and merge sort need about
n log2 n comparisons on every input. A quicksort
with a pivot taken from the end of the range would need
n2/2 comparisons on sorted data; the middle element avoids
that for sorted and reversed input.
$ gm2 -fiso counting.mod Samples.o Sorts.o -o counting $ ./counting input insertion quick merge random 977994 29280 19423 sorted 1999 20010 11088 reversed 1999000 20018 10864 equal 1999 20192 11088
Sorting records
The sorts in Sorts work on integers, but they can order
records too: the program sorts an array of indexes into the record table
and leaves the records in place. The comparators compare the records the
indexes point to.
MODULE ranking;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Assign, Compare, CompareResults, Length;
FROM Sorts IMPORT QuickSort, MergeSort;
CONST
N = 8;
TYPE
Player = RECORD
name: ARRAY [0..15] OF CHAR;
points: CARDINAL
END;
VAR
players: ARRAY [0..N - 1] OF Player;
order, tmp: ARRAY [0..N - 1] OF INTEGER;
PROCEDURE Set(i: CARDINAL; name: ARRAY OF CHAR; points: CARDINAL);
BEGIN
Assign(name, players[i].name);
players[i].points := points;
order[i] := i
END Set;
PROCEDURE ByName(i, j: INTEGER): BOOLEAN;
BEGIN
RETURN Compare(players[i].name, players[j].name) = less
END ByName;
PROCEDURE ByPoints(i, j: INTEGER): BOOLEAN;
BEGIN
RETURN players[i].points > players[j].points
END ByPoints;
PROCEDURE Show(title: ARRAY OF CHAR);
VAR
i, k: CARDINAL;
BEGIN
WriteString(title); WriteLn;
FOR i := 0 TO N - 1 DO
WriteString(" "); WriteString(players[order[i]].name);
FOR k := Length(players[order[i]].name) TO 8 DO WriteString(" ") END;
WriteCard(players[order[i]].points, 3); WriteLn
END
END Show;
BEGIN
Set(0, "Viera", 12); Set(1, "Adam", 15); Set(2, "Mira", 12);
Set(3, "Oskar", 9); Set(4, "Lenka", 15); Set(5, "Boris", 12);
Set(6, "Ivan", 9); Set(7, "Dana", 12);
QuickSort(order, ByName);
Show("by name:");
MergeSort(order, tmp, ByPoints);
Show("by points, merge sort:");
QuickSort(order, ByName);
QuickSort(order, ByPoints);
Show("by points, quicksort:")
END ranking.
order starts as 0, 1, 2 and so on, and the sorts rearrange
it. ByName uses Compare from the ISO
Strings module, which returns less,
equal or greater. ByPoints puts higher
scores first. A sort that keeps equal elements in their previous order is
stable. After a stable merge sort by points, the players with
the same score are still in name order; quicksort is not stable and mixes
them up. Sorting indexes is also cheaper than moving large records.
$ gm2 -fiso ranking.mod Sorts.o -o ranking $ ./ranking by name: Adam 15 Boris 12 Dana 12 Ivan 9 Lenka 15 Mira 12 Oskar 9 Viera 12 by points, merge sort: Adam 15 Lenka 15 Boris 12 Dana 12 Mira 12 Viera 12 Ivan 9 Oskar 9 by points, quicksort: Lenka 15 Adam 15 Mira 12 Viera 12 Boris 12 Dana 12 Oskar 9 Ivan 9
Choosing a sort
Insertion sort is short, stable and fast on small or nearly sorted arrays, but its work grows with the square of the length. Quicksort is usually the fastest on large arrays and needs no extra memory, but it is not stable, and a bad choice of pivot makes it slow. Merge sort always needs about n log2 n comparisons and is stable, at the price of a second array. Many library sorts combine them: quicksort or merge sort for large ranges and insertion sort for short ones.
Source
Niklaus Wirth: Algorithms and Data Structures
In this article we have written insertion sort, quicksort and merge sort on open arrays, moved the test data into a module, collected the sorts in a module that takes comparators, counted their comparisons and sorted records through an index array. The searching article uses sorted arrays for binary search, and the procedure types article covers the comparator type.
Author
List all Modula-2 tutorials.