Algorithms

Check each element in order until the target is found — O(n), works on unsorted data.

Version 1.2.0 · current Versions: 1.2.0 1.1.0 1.0.0

Implementations

Sign in to open in IDE Sign in with your Zerethon account to create your own copy of this sample.

Files

README.md
# Linear Search

Zerethon Official Sample `linear-search`, version 1.2.0, TypeScript 7 (Node.js 22).

- `linear_search.ts` — the algorithm (this sample's JavaScript code, with types)
- `main.ts` — entry file: a short demonstration
- `test_linear_search.ts` — checks; set it as the entry file to run them (or Run ▾ → Run tests)

Every `.ts` file is type-checked (`--strict`) before anything runs; a type error stops the run.

This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/linear-search-visualizer
linear_search.ts
// Linear Search (Zerethon Official Sample: linear-search 1.2.0).

// Returns the index of target, or -1. Works on any (unsorted) array.
export function linearSearch(a: readonly number[], target: number): number {
    for (let i = 0; i < a.length; i++) {
        if (a[i] === target) return i;
    }
    return -1;
}
main.ts entry
import { linearSearch } from './linear_search';

const numbers: number[] = [38, 27, 43, 3, 9, 82, 10, 27];
console.log(`List: [${numbers.join(', ')}]`);
for (const target of [43, 27, 38, 5]) {
    const index = linearSearch(numbers, target);
    const result = index !== -1 ? `found at index ${index}` : 'not found';
    console.log(`search ${String(target).padStart(2)}: ${result}`);
}
test_linear_search.ts
// Checks for linearSearch. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.
import { strictEqual } from 'assert';
import { linearSearch } from './linear_search';

const cases: [number[], number, number][] = [
    [[], 1, -1],
    [[4], 4, 0],
    [[4], 5, -1],
    [[9, 3, 7], 9, 0],
    [[9, 3, 7], 7, 2],
    [[5, 1, 5, 1], 1, 1], // the first match wins
    [Array.from({ length: 100 }, (_, i) => 100 - i), 1, 99],
];

for (const [a, target, expected] of cases) {
    strictEqual(linearSearch(a, target), expected, `linearSearch([${a.slice(0, 5)}...], ${target})`);
}

console.log(`All ${cases.length} checks passed.`);

Source: Zerethon Official Sample. The same algorithm as the JavaScript implementation of this sample.