It works on any list#

Linear search never uses the order of the list. It checks each number from the left, so it works on a shuffled list just as well as a sorted one, and it stops at the first match.

624891754883012345
Marks of six students

Quick check

Quick check: You search these marks for 48. Which index does linear search return?

The code#

The same idea, as code. Slide the target to 5, a number that is not in the list, and watch it check every one before giving up.

Linear search, line by lineline 1
Try another target
  1. nums = [4, 2, 7, 1, 9, 3]
  2. target = 9
  3. answer = -1
  4. for i in range(len(nums)):
  5. if nums[i] == target:
  6. answer = i
  7. break
  8. print(answer)

Variables

nums

427193

Six numbers, in no particular order.

Step 1 of 16

The same function in Python, C++, C, Java and Go:

How long it takes#

The worst case is a target that is last, or not there at all: every number gets checked. Double the list and you double the checks. That is O(n) time, with O(1) extra space.

Quick check

Quick check: A list holds 10 lakh roll numbers, and the one you want is not in it. How many checks does linear search make?

When to use it#

SituationUse
The list is not sortedLinear search
The list is sorted and largeBinary search
The list is tinyLinear search, it is simpler
You want the first item that matches a conditionLinear search

What to remember#

  • Check each item from the left; stop at the first match, or return -1 at the end.
  • Works on any list, sorted or not.
  • O(n) time and O(1) extra space.