A linear-time algorithm has a running-time growth bound of O(n), where n measures input size. Its work grows at most proportionally to n in the case being analyzed; individual inputs may require less work. Linear growth is slower than quadratic O(n²) growth but faster than logarithmic O(log n) growth. section 7.2
Searching an array
A linear search checks array elements until it finds the target. If the target is last, it takes n checks; an absent target also requires scanning the whole array. A target near the beginning takes fewer checks. section 7.2
fn find(values: &[i32], number: i32) -> bool {
for i in 0..values.len() {
if values[i] == number {
return true;
}
}
false
}
The search returns as soon as it finds a match and otherwise examines every element. section 7.2
Specify whether a complexity describes the average or worst case. For example, hash table lookup is O(1) on average but can be O(n) in the worst case when collisions require a linear scan. section 7.2
Big O describes growth, not absolute runtime. A linear scan may be acceptable when n is reliably small; for large inputs or frequently repeated operations, eliminating work can matter. An algorithm with worse growth can still be faster at small input sizes. section 7.2
Eliminating repeated Fibonacci work
Recursive Fibonacci repeatedly calculates the same values. Memoization stores results for reuse, reducing the algorithm to linear time. In one Criterion benchmark for n = 10, the recursive version took roughly 157 ns and the memoized version roughly 44 ns. These measurements illustrate a particular run, not a guarantee for every workload. section 7.7
Listing 7.3 Generating a number in the Fibonacci sequence using recursion with memoization
pub fn fib_memoization(n: u64) -> u64 {
fn fib(n: u64, cache: &mut Vec<u64>) -> u64 {
if n <= 1 {
return n;
}
if cache[n as usize] == 0 {
let result = fib(n - 1, cache) + fib(n - 2, cache);
cache[n as usize] = result;
}
cache[n as usize]
}
let mut cache = vec![0; (n + 1) as usize];
fib(n, &mut cache)
}
The memoized implementation caches each computed result in a vector and reuses it on later calls. section 7.7
Measure implementations rather than choosing on complexity alone. Use a Criterion benchmark and run cargo bench to compare runtimes; CPU profiling can then help identify where the remaining time is spent. section 7.7







