Algorithms

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

Version 1.1.0 Versions: 1.2.0 1.1.0 1.0.0

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

README.md
# Linear Search

Zerethon Official Sample `linear-search`, version 1.1.0, Python 3.12.

- `linear_search.py` — the algorithm, as shown in Zerethon Tools
- `main.py` — entry file: a short demonstration
- `test_linear_search.py` — 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.py
"""Linear Search (Zerethon Official Sample: linear-search 1.1.0)."""


# Returns the index of target, or -1. Works on any (unsorted) list.
def linear_search(a, target):
    for i in range(len(a)):
        if a[i] == target:
            return i
    return -1
main.py entry
from linear_search import linear_search

numbers = [38, 27, 43, 3, 9, 82, 10, 27]
print("List:", numbers)
for target in (43, 27, 38, 5):
    index = linear_search(numbers, target)
    result = f"found at index {index}" if index != -1 else "not found"
    print(f"search {target:>2}: {result}")
test_linear_search.py
# Checks for linear_search. To run them, set this file as the entry file
# (the ▶ button next to it in Files) and press Run.
from linear_search import linear_search

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
    (list(range(100, 0, -1)), 1, 99),
]

for a, target, expected in cases:
    got = linear_search(a, target)
    assert got == expected, f"linear_search({a[:5]}..., {target}) = {got}, expected {expected}"

print(f"All {len(cases)} checks passed.")

Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Linear Search Visualizer.