Linear Search
See it animated in Zerethon Tools ↗Check each element in order until the target is found — O(n), works on unsorted data.
This is an older version. The current version is 1.2.0.
Implementations
Sign in to open in IDE
Sign in with your Zerethon account to create your own copy of this sample.
Files
# Linear Search
Zerethon Official Sample `linear-search`, version 1.1.0, PHP 8.4.
- `linear_search.php` — the algorithm, as shown in Zerethon Tools
- `main.php` — entry file: a short demonstration
- `test_linear_search.php` — checks; set it as the entry file to run them
This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/linear-search-visualizer
<?php
// Linear Search (Zerethon Official Sample: linear-search 1.1.0).
// The algorithm as shown in Zerethon Tools.
// Returns the index of target, or -1. Works on any (unsorted) array.
function linear_search(array $a, int $target): int {
foreach ($a as $i => $v) {
if ($v === $target) return $i;
}
return -1;
}
<?php
require __DIR__ . '/linear_search.php';
$numbers = [38, 27, 43, 3, 9, 82, 10, 27];
echo 'List: [' . implode(', ', $numbers) . "]\n";
foreach ([43, 27, 38, 5] as $target) {
$index = linear_search($numbers, $target);
$result = $index !== -1 ? "found at index {$index}" : 'not found';
printf("search %2d: %s\n", $target, $result);
}
<?php
// Checks for linear_search. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.
require __DIR__ . '/linear_search.php';
$cases = [
[[], 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
[range(100, 1), 1, 99],
];
foreach ($cases as [$a, $target, $expected]) {
$got = linear_search($a, $target);
if ($got !== $expected) {
fwrite(STDERR, "linear_search(..., {$target}) = {$got}, expected {$expected}\n");
exit(1);
}
}
echo 'All ' . count($cases) . " checks passed.\n";
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Linear Search Visualizer.