ZetCode

Searching in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

Searching answers one question: where is this value, or is it present at all? The answer can come from a scan of an unsorted array, a binary search of a sorted one, a sorted string list, or a dictionary. The methods differ in the work they require before the search and in the time they take per lookup. This article implements each one and compares them; the hash tables article builds the structure that makes dictionary lookup fast.

Linear search

Linear search examines the elements one by one until it finds the value or reaches the end. For an unsorted array it is the direct option and needs no setup. The function returns the index of the first match, or -1 when the value is absent.

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

type
  TIntArray = array of Integer;

function LinearSearch(const A: TIntArray; Value: Integer): Integer;
var
  I: Integer;
begin
  for I := Low(A) to High(A) do
    if A[I] = Value then
      Exit(I);
  Result := -1;
end;

var
  Data: TIntArray;

begin
  Data := [17, 4, 23, 8, 42, 15, 31];
  WriteLn('index of 23: ', LinearSearch(Data, 23));
  WriteLn('index of 99: ', LinearSearch(Data, 99));
end.

The value 23 is at index 2 and 99 is not in the array, so the second call returns -1. In the worst case the loop examines every element, which is n comparisons for n elements. For a small array, or for a search that happens once, that cost is irrelevant.

$ fpc -gl linear.pas
$ ./linear
index of 23: 2
index of 99: -1

Binary search

Binary search requires a sorted array. It compares the target with the middle element: if the target is smaller, the right half cannot contain it; if it is larger, the left half cannot. Each comparison halves the remaining range, so a thousand elements need about ten comparisons instead of a thousand.

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

type
  TIntArray = array of Integer;

function BinarySearch(const A: TIntArray; Value: Integer): Integer;
var
  Lo, Hi, Mid: Integer;
begin
  Lo := 0;
  Hi := Length(A) - 1;
  while Lo <= Hi do
  begin
    Mid := Lo + (Hi - Lo) div 2;
    if A[Mid] = Value then
      Exit(Mid)
    else if A[Mid] < Value then
      Lo := Mid + 1
    else
      Hi := Mid - 1;
  end;
  Result := -1;
end;

var
  Data: TIntArray;

begin
  Data := [3, 8, 12, 17, 23, 31, 42, 55, 68, 79];
  WriteLn('index of 23: ', BinarySearch(Data, 23));
  WriteLn('index of 42: ', BinarySearch(Data, 42));
  WriteLn('index of 4:  ', BinarySearch(Data, 4));
  WriteLn('index of 79: ', BinarySearch(Data, 79));
end.

The midpoint is computed as Lo + (Hi - Lo) div 2 rather than (Lo + Hi) div 2, so the addition cannot overflow for a very large array. The loop ends when the range is empty, which means the value is absent. The array must already be sorted; running binary search on unsorted data produces a wrong answer, not an error.

$ fpc -gl binary.pas
$ ./binary
index of 23: 4
index of 42: 6
index of 4:  -1
index of 79: 9

Searching a sorted TStringList

TStringList has a Sorted property. When it is true, Add inserts each string in order, and Find performs a binary search. IndexOf also uses the binary search when the list is sorted, so the two calls return the same position.

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

uses Classes, SysUtils;

var
  Names: TStringList;
  Index: Integer;

begin
  Names := TStringList.Create;
  try
    Names.Sorted := True;
    Names.Add('Alice');
    Names.Add('Bob');
    Names.Add('Caroline');
    Names.Add('Dan');
    WriteLn('sorted: ', Names.CommaText);
    if Names.Find('Caroline', Index) then
      WriteLn('found Caroline at ', Index)
    else
      WriteLn('Caroline not found');
    WriteLn('IndexOf Bob: ', Names.IndexOf('Bob'));
    WriteLn('IndexOf Xavier: ', Names.IndexOf('Xavier'));
  finally
    Names.Free;
  end;
end.

Find returns a Boolean and stores the position in its second argument; IndexOf returns the position directly and -1 when the string is absent. The list stays sorted as strings are added, which costs a little on insertion but makes every lookup logarithmic. Setting Sorted := True on a list that already contains unsorted data sorts it.

$ fpc -gl strfind.pas
$ ./strfind
sorted: Alice,Bob,Caroline,Dan
found Caroline at 2
IndexOf Bob: 1
IndexOf Xavier: -1

Dictionaries

A dictionary maps keys to values and finds a value by its key without scanning. The generic TDictionary<TKey, TValue> from Generics.Collections is the standard implementation. The next program counts how often each word appears; the key is the word and the value is the count.

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

uses SysUtils, Generics.Collections;

type
  TCountMap = specialize TDictionary<string, Integer>;

const
  Words: array[1..8] of string = (
    'apple', 'banana', 'apple', 'cherry',
    'banana', 'apple', 'date', 'cherry');

var
  Counts: TCountMap;
  I, N: Integer;

begin
  Counts := TCountMap.Create;
  try
    for I := 1 to 8 do
    begin
      if Counts.TryGetValue(Words[I], N) then
        Counts[Words[I]] := N + 1
      else
        Counts.Add(Words[I], 1);
    end;
    WriteLn('distinct words = ', Counts.Count);
    WriteLn('apple  = ', Counts['apple']);
    WriteLn('banana = ', Counts['banana']);
    WriteLn('cherry = ', Counts['cherry']);
    WriteLn('date   = ', Counts['date']);
  finally
    Counts.Free;
  end;
end.

TryGetValue distinguishes a missing key from a stored zero, which the indexer alone cannot do. The indexer then updates the existing entry; Add is used only for a new word. The dictionary holds four distinct keys, and the counts are three, two, two, and one. A dictionary does not preserve insertion order, so a report should sort the keys before printing them.

$ fpc -gl wordcount.pas
$ ./wordcount
distinct words = 4
apple  = 3
banana = 2
cherry = 2
date   = 1

Choosing a method

Linear search is the simplest and needs no preparation, but it examines every element in the worst case. Binary search is much faster but requires sorted data. A sorted TStringList gives binary search for strings with very little code. A dictionary gives expected constant-time lookup, at the cost of extra memory and a hash function that distributes the keys well.

The choice follows the data. If the array is built once and searched many times, sort it and use binary search. If keys are inserted and removed while the program runs, a dictionary is the natural container. The hash tables article opens the dictionary and builds the underlying table by hand, so the constant-time promise becomes visible.

Next steps

The sorting article produces the sorted arrays that binary search needs, and the generics article explains the dictionary type in more detail. The hash tables article implements collisions and probing, and the binary trees article offers a third lookup structure whose shape adapts to the data.

Source

Free Pascal Reference guide

Free Pascal TStringList

Binary search algorithm on Wikipedia

In this article we searched an unsorted array linearly, halved the range with binary search, queried a sorted string list, counted words with a dictionary, and compared the methods. The series continues with hash tables 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.