Linear Search
Posted by Dustin Boston in Algorithm.
Linear Search is a straightforward algorithm for finding a specific element in a list. It sequentially checks each element until the target is found or the list ends, making it simple and effective for unsorted data but inefficient for large datasets.
References
- Cormen, T, Leiserson, C, Rivest, R, and Stein, C. (2001).
Introduction to Algorithms. (2nd ed). The MIT Press.
Source Code Listing
code.ts
// @file Linear Search
// @author Dustin Boston
export function linearSearch<T>(list: T[], target: T): number | undefined {
for (const [index, element] of list.entries()) {
if (element === target) {
return index; // Target found, return the index.
}
}
return undefined;
}
test.ts
import {test, expect, describe} from "bun:test";
import {linearSearch} from "./code.ts";
describe("Linear Search", () => {
test("Found", () => {
const a = [5, 2, 4, 6, 1, 3];
const resultA = linearSearch(a, 6);
expect(resultA).toBe(3);
});
test("Not Found", () => {
const b = [31, 41, 59, 26, 41, 58];
const resultB = linearSearch(b, 6);
expect(resultB).toBeUndefined();
});
});