Searching

Linear Search

Target:
Size:14
Visualizer is loading, please wait...
Execution Narrative
Step 1 of 9Start
Line 1
Starting Linear Search for target 55 across 14 elements.
Comparisons0
Operations0

Overview & Concept

Linear Search (Sequential Search) is the simplest search algorithm. It inspects every element in a collection one by one from beginning to end until a match is found or the collection is exhausted. It requires zero pre-conditions and operates on both unsorted and sorted data structures.

How It Works

Sequential Scanning: Begins at index 0 and advances incrementally to index n - 1.

Element Comparison: Evaluates current element A[i] against target value.

Immediate Termination: Returns index i immediately upon match detection.

Exhaustion Check: If loop reaches end of array without matching, returns -1 (not found).

Step-by-Step Execution

1. Start at BeginningSet index pointer i = 0.
2. Compare with TargetCompare A[i] with target value.
3. Match CheckIf A[i] == target, return index i.
4. Increment or TerminateIf i < n - 1, increment i and repeat. Otherwise, return -1.

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(1)O(n)O(n)O(1)
ExplanationOptimal input arrangement minimizing operations.Expected time for uniformly distributed randomized inputs.Adversarial degenerate conditions requiring full traversal.Auxiliary memory allocated beyond original input size.

Pseudocode & Invariants

Algorithm Logic
procedure linearSearch(A, target):
  for i = 0 to length(A) - 1:
    if A[i] == target:
      return i // target found
  end for
  return -1 // target not found
Algorithmic Invariants
  • Absence Invariant: For all k < i, A[k] != target.
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

Advantages & Disadvantages

Key Advantages

  • •Works on unsorted arrays and linked lists without prior preparation.
  • •O(1) auxiliary space.
  • •O(1) best case if target is at index 0.

Trade-offs & Limitations

  • •O(n) linear search time: slow for large datasets.

Real-World Applications

Searching Unsorted Small Lists

Looking up items in small configs or user inputs.

Single-Pass Streaming Filters

Searching logs or streaming network packets.

Decision Guide: When to Use

Ideal Scenarios

  • ✓When the collection is unsorted and will only be searched once or twice.
  • ✓When collection size is very small (n < 20).

Consider Alternatives When

  • ✕When performing repeated searches on large datasets (sort once and use Binary Search or Hash Table).

Compare trade-offs and complexity across complementary tools in AlgoViz.