{
    "slug": "searching_algorithms",
    "term": "Searching Algorithms",
    "category": "algorithms",
    "difficulty": "intermediate",
    "short": "Linear search is O(n) and works on any array. Binary search is O(log n) but requires a sorted array. Hash lookup is O(1) and the right choice for most in-memory searches.",
    "long": "Linear search: scan each element — O(n), works on unsorted data, unavoidable for some problems. Binary search: halve the search space each step — O(log n), requires sorted data. Finding the midpoint: mid = left + (right - left) / 2 (avoids integer overflow). Binary search applications: finding a value in a sorted array, searching a monotonic function, lower/upper bounds. Hash lookup (PHP array, SplHashMap): O(1) average — best for repeated lookups. For database queries, indexes implement B-tree search (O(log n)).",
    "aliases": [
        "binary search",
        "linear search",
        "hash lookup",
        "search algorithm"
    ],
    "tags": [
        "algorithms",
        "searching",
        "performance"
    ],
    "misconception": "Binary search is always better than linear search — binary search requires sorted data and has overhead that makes it slower than linear search for small arrays (< ~20 elements).",
    "why_it_matters": "Replacing in_array() (linear) with array_flip() + isset() (hash lookup) is O(n) vs O(1) — a common PHP optimisation that turns quadratic loops into linear ones.",
    "common_mistakes": [
        "Binary search on unsorted data — produces wrong results silently.",
        "Not using array_flip() for repeated membership tests — in_array is O(n) per call; flip once for O(1).",
        "Integer overflow in binary search midpoint: (left + right) / 2 — use left + (right - left) / 2.",
        "Off-by-one errors in binary search boundaries — test with arrays of size 0, 1, 2, and even/odd."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "big_o_notation",
        "hash_table",
        "sorting_algorithms",
        "two_pointer_technique"
    ],
    "prerequisites": [
        "big_o_notation",
        "hash_table",
        "binary_tree"
    ],
    "refs": [
        "https://en.wikipedia.org/wiki/Binary_search_algorithm"
    ],
    "bad_code": "// Linear search in loop — O(n²):\n$allowed = ['admin', 'editor', 'viewer']; // Could be 1000 roles\nforeach ($users as $user) {\n    if (in_array($user->role, $allowed)) { // O(n) per user\n        grantAccess($user);\n    }\n}",
    "good_code": "// Hash lookup — O(1) per user, O(n) total:\n$allowed = array_flip(['admin', 'editor', 'viewer']); // Flip once\nforeach ($users as $user) {\n    if (isset($allowed[$user->role])) { // O(1)\n        grantAccess($user);\n    }\n}\n\n// Binary search for sorted data:\nfunction binarySearch(array $arr, int $target): int {\n    $left = 0; $right = count($arr) - 1;\n    while ($left <= $right) {\n        $mid = $left + intdiv($right - $left, 2); // Avoids overflow\n        if ($arr[$mid] === $target) return $mid;\n        $arr[$mid] < $target ? ($left = $mid + 1) : ($right = $mid - 1);\n    }\n    return -1;\n}",
    "quick_fix": "For sorted arrays use binary search (O(log n)); for unsorted use hash lookup after array_flip (O(1)); avoid linear in_array() on large datasets in hot paths",
    "severity": "medium",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/searching_algorithms",
        "html_url": "https://codeclaritylab.com/glossary/searching_algorithms",
        "json_url": "https://codeclaritylab.com/glossary/searching_algorithms.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Searching Algorithms](https://codeclaritylab.com/glossary/searching_algorithms) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/searching_algorithms"
            }
        }
    }
}