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.0.0, Node.js 22.
- `linear_search.js` — the algorithm, as shown in Zerethon Tools
- `main.js` — entry file: a short demonstration
- `test_linear_search.js` — 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
// Linear Search (Zerethon Official Sample: linear-search 1.0.0).
// Returns the index of target, or -1. Works on any (unsorted) array.
function linearSearch(a, target) {
for (let i = 0; i < a.length; i++) {
if (a[i] === target) return i;
}
return -1;
}
module.exports = { linearSearch };
const { linearSearch } = require('./linear_search');
const numbers = [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}`);
}
// Checks for linearSearch. To run them, set this file as the entry file
// (the ▶ button next to it in Files) and press Run.
const assert = require('assert');
const { linearSearch } = require('./linear_search');
const 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
[Array.from({ length: 100 }, (_, i) => 100 - i), 1, 99],
];
for (const [a, target, expected] of cases) {
assert.strictEqual(linearSearch(a, target), expected, `linearSearch([${a.slice(0, 5)}...], ${target})`);
}
console.log(`All ${cases.length} checks passed.`);
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Linear Search Visualizer.