Comprehensive Study Guide: Linear Search, Binary Search, and Big O Complexity Analysis
Foundational Data Structures: Arrays and Strings
Array Fundamentals and Definition:
- Arrays serve as a primary, foundational data structure across computer science, designed to store ordered collections of elements.
- Arrays can store heterogeneous types of data, including nested structures such as other arrays.
- Elements are arranged linearly, where each item occupies a specific position defined by a numerical index.
- Example array containing numerical elements:
- Element values:
[55, 66, 44, 32, 34, 56, 76, 89, 21] - Corresponding indices:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Memory Architecture and Address Calculation:
- Array elements are allocated contiguously (side by side) in system memory.
- The index acts as an offset counter representing the number of element positions from the start of the memory block, which explains why arrays are zero-indexed ( for the first element).
- Given a starting base memory address and a fixed data type size, any element can be accessed in a single direct mathematical operation.
- Calculation formula for memory location:
- Illustrative scenario where array starts at base address and each integer occupies :
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Index (): Memory address
- Because calculating the address requires only a single addition and multiplication step, array lookup by index executes in constant time () regardless of total array size.
Basic Primitive Data Types in Arrays:
- Integer: Stores whole numbers (e.g., , ).
- Real (float): Stores numbers containing fractional or decimal components (e.g., , ).
- Boolean: Stores binary truth values (
True,False). - Character: Stores a single typographical symbol, letter, or digit (e.g.,
'a','7'). - String: Stores arbitrary contiguous sequences of textual characters, such as words, phrases, or location names (e.g.,
'hello').
String Properties and Length Notation:
- Strings operate identically to arrays of characters, meaning each character holds a distinct position accessed via a zero-based index.
- For the string , the character index mapping is:
- Index :
'h' - Index :
'e' - Index :
'l' - Index :
'l' - Index :
'o' - String length is formally denoted with vertical bars as .
- For , the length is .
Worked Example: Indexing and Length Operations:
- Let be the array
[1, 1, 2, 3, 5, 8, 13, 21]with indices spanning to . - Solving expression :
- Solving expression :
- Total number of elements in is , so .
- Solving expression :
- Let be the array
Linear Search Algorithm
Principles of Linear Search:
- Linear search represents the most straightforward sequential search strategy.
- It is strictly required when inspecting unordered or unsorted datasets where no sorting assumptions can be made.
- The algorithm traverses elements sequentially from left to right, comparing each encountered value against a specified target value .
- Traversal terminates immediately once the target is matched; if the end of the array is reached without matching, the algorithm concludes that is absent.
- In the worst case, every single element must be evaluated, making execution duration directly proportional to the dataset length ().
Formal Pseudocode:
- Structured pseudocode implementation (
linear_search.pseudo):text 1 X = [55, 66, 44, 32, 34, 56, 76, 89, 21] 2 T = 34 3 FOR I = 0 TO LEN(X) - 1 4 IF X[I] = T THEN 5 RETURN I 6 ENDIF 7 NEXT I 8 RETURN -1 9 END - Line 4 compares array element with target .
- Line 5 exits immediately upon discovery, returning index .
- Line 8 executes only after the entire loop concludes without finding , returning to denote absence.
- Structured pseudocode implementation (
Step-by-Step Traversal Trace ():
- Target search on array for :
- Step 1 (): . Evaluation: . Continue loop.
- Step 2 (): . Evaluation: . Continue loop.
- Step 3 (): . Evaluation: . Continue loop.
- Step 4 (): . Evaluation: . Continue loop.
- Step 5 (): . Evaluation: . Match confirmed; return index .
Linear Search Trace Table ():
- Tracing array for :
- Step 1: Index , , Match: No
- Step 2: Index , , Match: No
- Step 3: Index , , Match: No
- Step 4: Index , , Match: No
- Step 5: Index , , Match: No
- Step 6: Index , , Match: No
- Step 7: Index , , Match: No
- Step 8: Index , , Match: Yes,
RETURN 7
Python Implementation:
- Script implementation (
linear_search.py): ```python numbers = [4, 5, 6, 7, 3, 2, 10, 12, 13, 20]
def linear_search(array, target): for i in range(len(array)): if array[i] == target: return i # Algorithm stops here: target found at index i return -1 # Algorithm returns -1 if target element is not found
print(linear_search(numbers, 2)) # Returns 5 (2 is located at index 5) print(linear_search(numbers, -2)) # Returns -1 (element absent) ```
- Script implementation (
Comparison Metrics Across Cases:
- Best Case: Target is located at the first position ( at ). Requires exactly comparison.
- Worst Case (Target Present at End): Target is at the final position ( at ). Requires comparisons ( comparisons).
- Worst Case (Target Absent): Target is not in the array (). Requires checking all elements ( comparisons) before exiting and returning .
- Average Case: On average, approximately half the elements in the collection are inspected ( comparisons), scaling linearly as .
Binary Search Algorithm
- Divide-and-Conquer Methodology:
- Binary search requires the dataset to be sorted beforehand (numerical or alphabetical order).
- The algorithm uses a divide-and-conquer paradigm: on every cycle, it evaluates the midpoint value of the current search field and halves the remaining candidate elements.
- If data is sorted in ascending order, comparisons check whether the target is smaller or larger than the midpoint; for descending order, these comparisons are inverted.
- Physical Metaphor: Flipping open a physical dictionary at the midpoint, checking whether the target word alphabetically precedes or follows the current page, discarding the irrelevant half of the pages, and repeating until located.

Algorithm Flowchart Logic:
- 1. Start: Receive sorted array and target .
- 2. Search Field Check: Is the search field empty ()?
- If Yes: Output and stop.
- If No: Compute middle index: .
- 3. Target Check: Does ?
- If Yes: Output and stop.
- If No: Evaluate whether .
- If Yes: Discard and the entire left half; update .
- If No: Discard and the entire right half; update .
- 4. Repeat process with updated boundaries.
Binary Search Pseudocode:
- Structured pseudocode implementation (
binary_search.pseudo):text 1 X = [21, 32, 34, 44, 55, 56, 66, 76, 89] 2 T = 34 3 start = 0 4 end = LEN(X) 5 WHILE start < end 6 mid = (start + end) DIV 2 7 IF X[mid] = T THEN 8 RETURN mid 9 ELSEIF X[mid] < T THEN 10 start = mid + 1 11 ELSE 12 end = mid 13 ENDIF 14 ENDWHILE 15 RETURN -1 - The active search field extends from index to .
- Structured pseudocode implementation (
Step-by-Step Traversal Trace ():
- Target search on sorted array :
- Step 1:
- ,
- Check value:
- Comparison: . Because , discard and the right half.
- Boundary update:
- Step 2:
- ,
- Check value:
- Comparison: . Target matches midpoint value;
RETURN 2.
Trace Table for Target ():
- Binary search trace on sorted array for target :
- Step 1: , , , . Action: , update .
- Step 2: , , , . Action: ,
RETURN 6.
Python Implementation:
Script implementation (
binary_search.py): ```python def binary_search(arr, t): start = 0 # Starts equal to 0 (updated in loop) end = len(arr) # Set equal to size of inputwhile start < end: # Stopping condition when search field is empty mid_point = (start + end) // 2 # Define middle index
# If target is at midpoint, return index immediately if arr[mid_point] == t: return mid_point # If midpoint < target, shift lower bound past midpoint if arr[mid_point] < t: start = mid_point + 1 # If midpoint > target, shift upper bound to midpoint elif arr[mid_point] > t: end = mid_pointreturn -1 # Target not found ```
Failure Demonstration on Unsorted Data:
- Executing binary search on unsorted data produces erroneous results because the algorithm discards elements based on false ordering assumptions.
- Demonstration searching for target in unsorted array :
- Step 1: , , , . Because , algorithm assumes must reside in the left half and discards the right half (indices through ). The target is at index and is improperly discarded.
- Step 2: , , , . Comparison: , discard right half; .
- Step 3: , , , . Comparison: , discard right half; .
- Step 4: , , , . Comparison: , discard right half; .
- Step 5: , . Search field is completely empty. Algorithm returns , incorrectly stating that is absent when it was present all along.
Binary Decision Tree Structure:
- A binary search across a sorted collection can be visualized as a balanced binary decision tree.
- For items (
[21, 32, 34, 44, 55, 56, 66, 76, 89]): - Level 1 (Comparison 1): Root at index (value ).
- Level 2 (Comparison 2): Left child at index (value ); Right child at index (value ).
- Level 3 (Comparison 3): Children at index (value ), index (value ), index (value ), index (value ).
- Level 4 (Comparison 4): Leaves at index (value ) and index (value ).
- With vertical levels, a maximum of comparisons is required to evaluate any of the values.
Mathematical Derivation of Comparison Bounds:
- Each successive comparison divides the remaining active items by .
- Starting with items, the number of elements remaining after successive halvings is:
- In the worst case, halving continues until exactly element remains:
- Number of worst-case comparisons as dataset grows:
- Doubling the input dataset size adds only additional comparison step ( logarithmic complexity).
Real-World Case Study: CCTV Investigation of Bike Theft:
- The Scenario: Police in Cambridge established an investigative policy refusing to review security CCTV footage if the potential theft window exceeded .
- Computer Science Counterargument: A computer scientist demonstrated that applying binary search would resolve the theft within approximately one hour even if surveillance footage spanned backwards to the dawn of humanity (IFLScience, 2023).
- Application: An investigator views the exact midpoint frame of the recording. If the bicycle is still present in the rack, the theft occurred after that timestamp; if the bicycle is gone, the theft occurred prior to that timestamp. Each check halves the remaining video duration.
- Mathematical Modeling: In 2025, a mathematician confirmed that no more than checks are necessary to reduce an continuous surveillance tape down to a precise window, taking around total at per review check (Kehoe, 2025).
- Cosmic Timescale Calculation:
- Assuming a continuous video recording spanning the entire age of the universe, estimated at (European Space Agency, 2013).
- Converting into seconds yields approximately .
- Number of halving operations needed to isolate the exact second of the theft: exactly ().
- To narrow the event down to an exact single video frame (at ): exactly .
Comparative Search Analysis
Structural Comparison Between Search Methods:
- Binary Search:
- Data Precondition: Requires strictly sorted data.
- Algorithmic Strategy: Divide and conquer.
- Search Field Manipulation: Halves the search space on each step.
- Time Complexity: Logarithmic growth ().
- Linear Search:
- Data Precondition: Operates on unsorted or arbitrary data.
- Algorithmic Strategy: Sequential exhaustive traversal.
- Search Field Manipulation: Decrements search field by element at each step.
- Time Complexity: Linear growth ().
Worst-Case Search Comparisons Across Dataset Sizes:
- When searching :
- Linear search requires up to .
- Binary search requires up to .
- When searching :
- Linear search requires up to .
- Binary search requires up to .
- When searching :
- Linear search requires up to .
- Binary search requires up to .
Big O Notation and Algorithmic Complexity
Historical Background of Big O Notation:
- Big O notation predates digital electronic computing.
- German mathematician Paul Bachmann first introduced the notation in 1894 within a treatise on analytic number theory.
- Fellow mathematician Edmund Landau adopted and popularized the notation across the mathematics community beginning in 1909.
- The letter 'O' represents the word "order" (Order of growth) (Tou, 2018).
Purpose of Computational Complexity:
- While an individual processor instruction executes in fractions of a microsecond, cumulative operations across large datasets compound drastically.
- Password Brute-Force Metric: An algorithm executing an exhaustive brute-force search across every permutation of a password requires over to complete on a standard desktop computer (Craddock & Ellis, 2016, p. 94).
Scope and Conceptual Boundaries of Big O:
- What Big O Describes: Provides a standardized theoretical framework to classify algorithms by their worst-case asymptotic upper bound, denoted , where represents the upper limit growth rate (Craddock & Ellis, 2016, p. 94).
- What Big O Does Not Tell Us: It does not calculate exact execution duration or wall-clock runtime in seconds. Instead, it predicts how execution time scales as input size expands from small inputs (e.g., elements) to massive scales (e.g., or elements) (Craddock & Ellis, 2016, p. 94).
Hierarchy of Time Complexities (Ordered Slowest to Fastest Growing):
- 1. Constant Complexity:
- 2. Logarithmic Complexity:
- 3. Linear Complexity:
- 4. Log-linear Complexity:
- 5. Quadratic Complexity:
- 6. Cubic Complexity:
- 7. Exponential Complexity:
- 8. Factorial Complexity:
Detailed Taxonomy of Complexity Classes:
- Constant Complexity :
- Execution duration remains invariant regardless of whether input size is small or vast.
- Example: Accessing or updating an array element directly via its numerical index (
arr[2]), or constant-time hashmap insertions. - Python array access (
array_access.py):python names = ['james', 'alex', 'matthew', 'charlotte', 'daniel'] print(names[0]) # Accessing index 0 runs in O(1) names[2] = 'matt' # Mutating index 2 runs in O(1)

Logarithmic Complexity :
- Execution runtime grows much slower than the underlying dataset.
- Execution increments by a single additional step each time the dataset size doubles.
- Example: Binary search requires at most for , for , and for .
Linear Complexity :
- Execution runtime expands at the exact same proportional rate as input size.
- Example: Accumulating a running sum of all items in an array via a single loop. A set containing takes ; a set containing takes (Craddock & Ellis, 2016, p. 95).
Polynomial Complexity ():
- Runtime increases substantially faster than linear algorithms.
- Quadratic (): Processing requires ; require ; require .
- Cubic (): Scales even more steeply, requiring operations (Craddock & Ellis, 2016, p. 95).
Exponential Complexity (e.g., ):
Workload escalates at an explosive rate as input size increases.
An algorithm requiring steps needs for , for , and for .
Evaluating produces a number with , demanding trillions of years on conventional computers (Craddock & Ellis, 2016, p. 95).
Brute-Force Password Cracking Times:
Theoretical duration required to test every permutation at an evaluation speed of ():
Length 6:
- Numbers (): Instantly
- Lowercase (): Instantly
- Uppercase & lowercase (): Instantly
- Letters & numbers ():
- Letters, numbers & symbols ():
Length 8:
- Numbers: Instantly
- Lowercase:
- Uppercase & lowercase:
- Letters & numbers:
- Letters, numbers & symbols:
Length 10:
- Numbers: Instantly
- Lowercase:
- Uppercase & lowercase:
- Letters & numbers:
- Letters, numbers & symbols:
Length 12:
- Numbers:
- Lowercase:
- Uppercase & lowercase:
- Letters & numbers:
- Letters, numbers & symbols:
Length 14:
- Numbers:
- Lowercase:
- Uppercase & lowercase:
- Letters & numbers:
- Letters, numbers & symbols:
Impact When Data Size Doubts ():
Constant : Workload remains invariant (stays identical).
Logarithmic : Workload increases by .
Linear : Workload doubles ().
Log-linear : Workload increases by just over double ().
Quadratic : Workload quadruples (). If an algorithm requires for , it requires for .
Cubic : Workload increases eightfold ().
Exponential : Workload is squared ().
- Algorithm Efficiency vs. Hardware Power Benchmark:
Scenario: Processing () at a computing rate of ():
- A log-linear algorithm () finishes in approximately .
- A quadratic algorithm () requires approximately .
- Upgrading to hardware that is ten times faster reduces the quadratic runtime to roughly .
- Core Principle: Algorithmic optimization always outperforms hardware speed upgrades.
Working with Big O
Determining Big O from Source Code:
- Analysis Rule: Identify the most active instruction inside the function, and determine how many times that line runs as dataset size expands to .
- Constant Time Implementation ():
def first_item(items): return items[0] # Runs exactly 1 time regardless of input size ``` * **Linear Time Implementation ():**python def total(items): result = 0 for x in items: result += x # Loop body executes n times return result ```
- Quadratic Time Implementation ():
def has_duplicate(items): for i in range(len(items)): for j in range(len(items)): if i != j and items[i] == items[j]: # Executes n * n times return True return False ``` * **Logarithmic Time Implementation ():**python def halvings(n): steps = 0 while n > 1: n = n // 2 # Value halves on each cycle, running log2(n) times steps += 1 return steps ```
Rules for Simplifying Big O Expressions:
- 1. Retain only the fastest-growing term that dominates as .
- 2. Omit all multiplicative constant factors and additive constants.
- Simplification Examples:
- Expression simplifies to : Multiplicative factor and constant do not influence asymptotic scaling.
- Expression simplifies to : The quadratic term dominates. At , contributes out of the total .
- Expression simplifies to : Exponential growth quickly surpasses any polynomial term.
- Expression simplifies to : Contains no variable; workload remains fixed for all inputs.
Time and Space Complexity Profiles of Search Algorithms:
- Linear Search:
- Best-case Time Complexity: (target found at index )
- Average-case Time Complexity:
- Worst-case Time Complexity:
- Worst-case Space Complexity:
- Binary Search:
- Best-case Time Complexity: (target found at initial midpoint)
- Average-case Time Complexity:
- Worst-case Time Complexity:
- Worst-case Space Complexity:
Practice Exercises and Review Questions
Question 1: Array Length and Indexing:
- Prompt: Let . What is , and what is ?
- Answer: (the total count of elements). (counting from index : , , , ).
Question 2: Algorithm Selection on Unsorted Data:
- Prompt: Which search would you use on an unsorted list of names, and why?
- Answer: Linear search must be selected. Binary search cannot be applied because its divide-and-conquer logic requires sorted input.
Question 3: Worst-Case Comparisons on 64 Items:
- Prompt: A sorted list has . What is the most comparisons each search needs to find an item?
- Answer: Linear search requires up to . Binary search requires at most (halving chain: , which yields halving steps plus final evaluation, or comparisons).
Question 4: Big O Classification:
- Prompt: Give the Big O time complexity of: accessing
arr[3]; linear search; binary search. - Answer: Accessing
arr[3]is ; linear search is ; binary search is .
- Prompt: Give the Big O time complexity of: accessing
Question 5: Trade-Off Analysis of Binary Search:
- Prompt: Give one advantage and one disadvantage of binary search compared with linear search.
- Answer:
- Advantage: Requires vastly fewer comparisons when querying large collections ( logarithmic scaling).
- Disadvantage: Demands that the target dataset be sorted before searching.
Question 6: Nested Loop Analysis and Simplification:
- Prompt: A function has a loop over the whole list inside another loop over the whole list. What is its Big O, and what is simplified?
- Answer: Nested loops over length run in steps, producing . The polynomial simplifies to by dropping the lower-order term and constant coefficient .
Independent Study and Bibliographic References
Curated Independent Learning Resources:
- Interactive Visualizer: Binary and Linear Search Visualisation (University of San Francisco Galles tool,
cs.usfca.edu/~galles/visualization/Search.html). - Video Demonstration: Searching algorithms (BBC Teach class clips,
bbc.co.uk/teach/class-clips-video/articles/z662pg8). - Instructional Guide: Extra reading on Big O notation (NeetCode,
neetcode.io/courses/lessons/big-o-notation). - Video Lecture: Big O notation (YouTube,
youtube.com/watch?v=kgBjXUE_Nwc&t=28). - Video Tutorial: Big O notation – a few examples (YouTube,
youtube.com/watch?v=-Eiw_-v__Vo). - Interactive Game: Binary search interactive game (Math The Beautiful,
maththebeautiful.com/binary-search). - Practical Exercises: Code breaker challenges – series 1 (101 Computing,
101computing.net/code-breaker-challenges). - Advanced Theory: P vs NP and computational complexity (YouTube,
youtube.com/watch?v=pQsdygaYcE4).
- Interactive Visualizer: Binary and Linear Search Visualisation (University of San Francisco Galles tool,
Subsequent Curriculum Preview:
- Upcoming unit examines search and sort algorithms (Week 2, Lecture 2).
- Focus topics: Utility of sorted data, algorithm tracing for bubble sort, insertion sort, merge sort, and quicksort using trace tables and pseudocode.
- Comparison counting, best/worst case scenarios, algorithmic stability, and time complexity classifications.
Academic References:
- Craddock, G., & Ellis, V. (2016). Essential Maths Skills for AS/A Level Computer Science. Hodder Education.
- European Space Agency. (2013, March 21). Planck reveals an almost perfect Universe. ESA Science & Exploration.
- IFLScience. (2023, January 26). Computer scientist attempts to get the police to find his stolen bike using math.
- Kehoe, C. (2025). The police won't investigate bike theft because there's too much CCTV to review. Why won't they adopt this simple mathematical trick? London Centric.
- Tou, E. R. (2018). Math Origins: Orders of Growth. Mathematical Association of America.