Linear Search

September 3, 2024 (2y ago)

Linear search is looking for a target item in an array. Linear search returns the index of the target if found. Linear search will raise and exception if not found.

Algorithm

  1. Iterate through entire array by index

    • Get value at the index
    • if value equals our target, return the index
  2. If iteration completes without finding the target, raise an exception

Example

Complexity

casescomplexitydescription
best caseO(1)target is the first item
average caseO(n)target is the middle element
worst caseO(n)target is not found

Example: String Search Algorithm

  1. Look for the existence of a target string in another string
  2. Return the index of the first occurrence of target
  3. Raise exception if target is not found

Pseudocode

  1. Set n = length of string
  2. Set m = length of target
  3. For i = 0 to n - m
  4. Set j = 0
  5. While j < m and target[i] equals string[i + j]
  6. increment j
  7. end while
  8. if j equals m then return i
  9. raise exception

Complexity

n is the length of the string and m is the length of the target

casescomplexitydescription
best caseO(m)target is at the beginning
average caseO(mn)target is in the middle
worst caseO(mn)target is not found

Topics