Modula-2 searching
last modified November 27, 2026 Modula-2
Searching finds the position of a value in a collection, or tells that the value is not there. This article covers the two basic methods for arrays: linear search, which works on any array, and binary search, which needs a sorted array and is much faster.
The last example uses the Samples and Sorts
modules from the sorting article; they are
compiled the same way and not reprinted here. All examples are compiled
with -fiso.
Linear search
A linear search compares the value with each element in turn, from the first to the last, and stops at the first match.
MODULE linear;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
VAR
data: ARRAY [0..9] OF INTEGER;
PROCEDURE Find(VAR a: ARRAY OF INTEGER; x: INTEGER; VAR pos: CARDINAL): BOOLEAN;
VAR
i: CARDINAL;
BEGIN
FOR i := 0 TO HIGH(a) DO
IF a[i] = x THEN
pos := i;
RETURN TRUE
END
END;
RETURN FALSE
END Find;
PROCEDURE Look(x: INTEGER);
VAR
pos: CARDINAL;
BEGIN
WriteInt(x, 4);
IF Find(data, x, pos) THEN
WriteString(" found at index "); WriteCard(pos, 0)
ELSE
WriteString(" not found")
END;
WriteLn
END Look;
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;
Look(18);
Look(7);
Look(3);
Look(40)
END linear.
Find returns TRUE and the index in the
VAR parameter pos when it finds the value, and
FALSE when it reaches the end. A function procedure returns
one value, so the second result goes through a VAR parameter.
The number 7 occurs twice, and the search reports the first occurrence.
$ gm2 -fiso linear.mod -o linear $ ./linear 18 found at index 4 7 found at index 1 3 found at index 9 40 not found
A sentinel
The loop of a linear search makes two tests per element: the end of the array and the value. Wirth's books save the first test with a sentinel, a copy of the searched value placed after the last element.
MODULE sentinel;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
CONST
N = 10;
VAR
data: ARRAY [0..N] OF INTEGER;
PROCEDURE Find(x: INTEGER): CARDINAL;
VAR
i: CARDINAL;
BEGIN
data[N] := x;
i := 0;
WHILE data[i] # x DO
INC(i)
END;
RETURN i
END Find;
PROCEDURE Look(x: INTEGER);
VAR
pos: CARDINAL;
BEGIN
pos := Find(x);
WriteInt(x, 4);
IF pos < N THEN
WriteString(" found at index "); WriteCard(pos, 0)
ELSE
WriteString(" not found")
END;
WriteLn
END Look;
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;
Look(18);
Look(3);
Look(40)
END sentinel.
The array has one extra element, data[N], which receives the
searched value before the loop. The loop is then sure to stop, and it only
compares values. When it stops at index N, it has found the
sentinel, which means that the value is not among the real elements. The
trick needs a spare element that the search may overwrite, so it works on
the program's own array, not on an open array parameter.
$ gm2 -fiso sentinel.mod -o sentinel $ ./sentinel 18 found at index 4 3 found at index 9 40 not found
Searching records
The elements are often records, and the search compares one field, the key. Here the key is the name of a country, and the search returns its capital.
MODULE capitals;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Strings IMPORT Equal;
TYPE
Name = ARRAY [0..15] OF CHAR;
Country = RECORD
name, capital: Name
END;
VAR
countries: ARRAY [0..5] OF Country;
PROCEDURE Set(i: CARDINAL; name, capital: Name);
BEGIN
countries[i].name := name;
countries[i].capital := capital
END Set;
PROCEDURE Capital(name: ARRAY OF CHAR; VAR capital: Name): BOOLEAN;
VAR
i: CARDINAL;
BEGIN
FOR i := 0 TO HIGH(countries) DO
IF Equal(countries[i].name, name) THEN
capital := countries[i].capital;
RETURN TRUE
END
END;
RETURN FALSE
END Capital;
PROCEDURE Look(name: ARRAY OF CHAR);
VAR
capital: Name;
BEGIN
WriteString(name);
IF Capital(name, capital) THEN
WriteString(": "); WriteString(capital)
ELSE
WriteString(": unknown")
END;
WriteLn
END Look;
BEGIN
Set(0, "Slovakia", "Bratislava"); Set(1, "Austria", "Vienna");
Set(2, "Hungary", "Budapest"); Set(3, "Poland", "Warsaw");
Set(4, "Czechia", "Prague"); Set(5, "Slovenia", "Ljubljana");
Look("Hungary");
Look("Slovenia");
Look("slovakia");
Look("Croatia")
END capitals.
Strings cannot be compared with =, so Capital
uses Equal from the ISO Strings module. The
comparison is exact: slovakia with a lower-case letter is not
found. The result parameter has the named type Name, because
an open array cannot be the target of an assignment.
$ gm2 -fiso capitals.mod -o capitals $ ./capitals Hungary: Budapest Slovenia: Ljubljana slovakia: unknown Croatia: unknown
Binary search
In a sorted array, one comparison with the middle element tells which half can contain the value. Binary search keeps halving the range until it finds the value or the range is empty. The program prints every step.
MODULE binary;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
VAR
data: ARRAY [0..11] OF INTEGER;
i: CARDINAL;
PROCEDURE Find(VAR a: ARRAY OF INTEGER; x: INTEGER; VAR pos: CARDINAL): BOOLEAN;
VAR
lo, hi, mid: CARDINAL;
BEGIN
lo := 0;
hi := HIGH(a) + 1;
WHILE lo < hi DO
mid := (lo + hi) DIV 2;
WriteString(" ["); WriteCard(lo, 0); WriteString(".."); WriteCard(hi - 1, 0);
WriteString("] a["); WriteCard(mid, 0); WriteString("] = ");
WriteInt(a[mid], 0); WriteLn;
IF a[mid] < x THEN
lo := mid + 1
ELSIF a[mid] > x THEN
hi := mid
ELSE
pos := mid;
RETURN TRUE
END
END;
RETURN FALSE
END Find;
PROCEDURE Look(x: INTEGER);
VAR
pos: CARDINAL;
BEGIN
WriteString("looking for "); WriteInt(x, 0); WriteLn;
IF Find(data, x, pos) THEN
WriteString(" found at index "); WriteCard(pos, 0)
ELSE
WriteString(" not found")
END;
WriteLn
END Look;
BEGIN
FOR i := 0 TO HIGH(data) DO
data[i] := 3 * i + 1
END;
Look(22);
Look(1);
Look(20)
END binary.
The range is the half-open interval from lo up to, but not
including, hi; the program prints it as the closed range of
indexes. When the middle element is smaller than the value, the search
continues right of it, when it is larger, left of it. An empty range,
lo = hi, ends the search without a match. With a half-open
range, hi never goes below 0, so all indexes can be
CARDINAL. The array holds 1, 4, 7, …, 34, and twelve elements
need at most four steps.
$ gm2 -fiso binary.mod -o binary $ ./binary looking for 22 [0..11] a[6] = 19 [7..11] a[9] = 28 [7..8] a[8] = 25 [7..7] a[7] = 22 found at index 7 looking for 1 [0..11] a[6] = 19 [0..5] a[3] = 10 [0..2] a[1] = 4 [0..0] a[0] = 1 found at index 0 looking for 20 [0..11] a[6] = 19 [7..11] a[9] = 28 [7..8] a[8] = 25 [7..7] a[7] = 22 not found
A recursive binary search
Binary search is naturally recursive: searching a range means searching one of its halves. This version returns the index, or -1 when the value is not there.
MODULE recursive;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
data: ARRAY [0..11] OF INTEGER;
i: CARDINAL;
PROCEDURE Search(VAR a: ARRAY OF INTEGER; x: INTEGER; lo, hi: CARDINAL): INTEGER;
VAR
mid: CARDINAL;
BEGIN
IF lo >= hi THEN
RETURN -1
END;
mid := (lo + hi) DIV 2;
IF a[mid] < x THEN
RETURN Search(a, x, mid + 1, hi)
ELSIF a[mid] > x THEN
RETURN Search(a, x, lo, mid)
END;
RETURN mid
END Search;
PROCEDURE Find(VAR a: ARRAY OF INTEGER; x: INTEGER): INTEGER;
BEGIN
RETURN Search(a, x, 0, HIGH(a) + 1)
END Find;
BEGIN
FOR i := 0 TO HIGH(data) DO
data[i] := 3 * i + 1
END;
FOR i := 19 TO 23 DO
WriteInt(i, 2); WriteString(" -> index ");
WriteInt(Find(data, i), 0); WriteLn
END
END recursive.
Search calls itself on the right or the left half, and the
empty range is the base case. Every recursive call is the last thing the
procedure does, so the loop of the previous section is a direct
translation. The result is an INTEGER, because -1 is not a
valid index; the caller has to check it before using it as one.
$ gm2 -fiso recursive.mod -o recursive $ ./recursive 19 -> index 6 20 -> index -1 21 -> index -1 22 -> index 7 23 -> index -1
Counting probes
A probe is one comparison of the searched value with an element. The program counts the average number of probes for arrays of growing size, for values that are present and for values that are not.
MODULE probes;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;
CONST
Max = 10000;
VAR
data: ARRAY [0..Max - 1] OF INTEGER;
count, size, k: CARDINAL;
PROCEDURE Linear(x: INTEGER; n: CARDINAL);
VAR
i: CARDINAL;
BEGIN
i := 0;
WHILE i < n DO
INC(count);
IF data[i] = x THEN RETURN END;
INC(i)
END
END Linear;
PROCEDURE Binary(x: INTEGER; n: CARDINAL);
VAR
lo, hi, mid: CARDINAL;
BEGIN
lo := 0; hi := n;
WHILE lo < hi DO
INC(count);
mid := (lo + hi) DIV 2;
IF data[mid] < x THEN lo := mid + 1
ELSIF data[mid] > x THEN hi := mid
ELSE RETURN
END
END
END Binary;
PROCEDURE Average(n: CARDINAL; binary: BOOLEAN; offset: INTEGER);
VAR
i: CARDINAL;
x: INTEGER;
BEGIN
count := 0;
FOR i := 0 TO n - 1 DO
x := data[i] + offset;
IF binary THEN Binary(x, n) ELSE Linear(x, n) END
END;
WriteFixed(FLOAT(count) / FLOAT(n), 1, 10)
END Average;
BEGIN
FOR k := 0 TO Max - 1 DO
data[k] := 2 * k + 1
END;
WriteString(" linear search binary search"); WriteLn;
WriteString(" n found missing found missing"); WriteLn;
size := 10;
WHILE size <= Max DO
WriteCard(size, 5);
Average(size, FALSE, 0); Average(size, FALSE, 1);
Average(size, TRUE, 0); Average(size, TRUE, 1);
WriteLn;
size := size * 10
END
END probes.
The array holds the odd numbers 1, 3, 5 and so on, so every element can be
searched for, and adding 1 to an element gives a value that is missing.
Average searches once for every element, or for every missing
neighbour, and divides the probes by n. A linear search needs
n/2 probes on average to find a value and n to rule it out.
Binary search needs about log2 n: ten times more elements
cost only three or four more probes.
$ gm2 -fiso probes.mod -o probes
$ ./probes
linear search binary search
n found missing found missing
10 5.5 10.0 2.9 3.5
100 50.5 100.0 5.8 6.7
1000 500.5 1000.0 9.0 10.0
10000 5000.5 10000.0 12.4 13.4
Ranges of equal elements
When a sorted array contains duplicates, binary search can find the first and the last of them. The lower bound is the first index whose element is not smaller than the value; the upper bound is the first index whose element is larger.
MODULE bounds;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM Samples IMPORT Fill, Show;
FROM Sorts IMPORT QuickSort;
VAR
data: ARRAY [0..15] OF INTEGER;
i: CARDINAL;
v: INTEGER;
PROCEDURE Less(a, b: INTEGER): BOOLEAN;
BEGIN
RETURN a < b
END Less;
(* the first index whose element is not smaller than x *)
PROCEDURE LowerBound(VAR a: ARRAY OF INTEGER; x: INTEGER): CARDINAL;
VAR
lo, hi, mid: CARDINAL;
BEGIN
lo := 0; hi := HIGH(a) + 1;
WHILE lo < hi DO
mid := (lo + hi) DIV 2;
IF a[mid] < x THEN lo := mid + 1 ELSE hi := mid END
END;
RETURN lo
END LowerBound;
(* the first index whose element is larger than x *)
PROCEDURE UpperBound(VAR a: ARRAY OF INTEGER; x: INTEGER): CARDINAL;
VAR
lo, hi, mid: CARDINAL;
BEGIN
lo := 0; hi := HIGH(a) + 1;
WHILE lo < hi DO
mid := (lo + hi) DIV 2;
IF a[mid] <= x THEN lo := mid + 1 ELSE hi := mid END
END;
RETURN lo
END UpperBound;
BEGIN
Fill(data, 4);
FOR i := 0 TO HIGH(data) DO
data[i] := data[i] MOD 10
END;
QuickSort(data, Less);
Show("data:", data);
FOR v := 0 TO 9 DO
WriteInt(v, 2); WriteString(": from ");
WriteCard(LowerBound(data, v), 2); WriteString(" to ");
WriteCard(UpperBound(data, v), 2); WriteString(", ");
WriteCard(UpperBound(data, v) - LowerBound(data, v), 0);
WriteString(" times"); WriteLn
END
END bounds.
The two procedures differ only in < and
<=. They do not stop at a match but always narrow the range
to one position. The elements equal to x lie between the two
bounds, so their difference is the number of occurrences. For a missing
value both bounds are equal, and they give the position where the value
would have to be inserted to keep the array sorted. The data are sixteen
numbers from Fill, reduced to one digit and sorted with
QuickSort.
$ gm2 -fiso -c Samples.mod $ gm2 -fiso -c Sorts.mod $ gm2 -fiso bounds.mod Samples.o Sorts.o -o bounds $ ./bounds data: 0 0 0 0 2 2 3 3 4 4 4 4 6 8 8 9 0: from 0 to 4, 4 times 1: from 4 to 4, 0 times 2: from 4 to 6, 2 times 3: from 6 to 8, 2 times 4: from 8 to 12, 4 times 5: from 12 to 12, 0 times 6: from 12 to 13, 1 times 7: from 13 to 13, 0 times 8: from 13 to 15, 2 times 9: from 15 to 16, 1 times
Choosing a search
Linear search works on any array, sorted or not, and is the fastest for a handful of elements. Binary search needs a sorted array but finds a value among a million elements in twenty probes. Sorting costs more than one linear search, so it pays off when the same array is searched many times. A hash table finds a key in a constant number of probes on average, but keeps the elements in no particular order.
Source
Niklaus Wirth: Algorithms and Data Structures
In this article we have searched arrays linearly, with and without a sentinel, looked up records by a string key, written binary search as a loop and as a recursive procedure, counted probes, and found ranges of equal elements with lower and upper bounds. The sorting article prepares arrays for binary search, and the recursion article covers recursive procedures.
Author
List all Modula-2 tutorials.