liveBook · Manning

Linear search

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A linear search examines elements sequentially in their data-structure order until it finds the sought value or reaches the end.

Linear search checks elements in their original order until it finds the sought value or reaches the end. It is the simplest natural search, but may inspect every element. section 2.1

Searching a gene

Represent a gene as an array of codons, then compare each codon with the target. For example, linearContains(gene, item: acg) returns true when the codon (.A, .C, .G) appears and false when the scan finishes without a match. func linearContains(_ array: Gene, item: Codon) -> Bool { for element in array where item == element { return true } return false } section 2.1

Use linear search when:

  • The data structure is not known to be sorted, so sequential inspection is the direct approach. section 2.1
  • The collection is small or simplicity matters more than reducing comparisons. section 2.1
  • A built-in Swift Sequence method is appropriate: contains() already performs a linear search and usually should be preferred. section 2.1
  • Performance needs comparison with binary search; timing million-element arrays makes the difference observable. section 2.5 section 2.4

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines the scan, implements it for codons and generic Swift collections, and identifies O(n) worst-case work.
Examples
Uses a gene of codons, the target codon ACG, a generic Swift function, and million-element timing exercises.
What it assumes
Assumes basic Swift arrays, loops, equality, and gene representations while demonstrating the search procedure from a concrete example.
What you can do after
Build it from scratch for codons or generic Equatable arrays, then compare its timing with binary search.
How it connects
Contrasts with binary search and relates to Swift Sequence.contains() and the ordering of data structures.

Also explained in

Compare how 5 books explain linear search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.