Skip to content
ExamSpine

Lesson 7.5

Linear search

Part 7: AlgorithmsReading, about 7 min3 exercises in this lesson, in Python2 exercises in this lesson, in Java

Java answers can't run on ExamSpine yet. You can still read Java, trace it, and put an answer's lines in order.

Linear search

By the end of this you will be able to write a linear search in Python and in Java that returns where a value is, or -1 when it is not there, and state its complexity with a reason.

How it is asked

Linear search is one of the few algorithms the course names, so expect to write it from memory. The new course has no past papers yet (the first exams are in May 2027), but expect three shapes:

  • Write a function (a method in Java) that returns the index of a value in a list or array, or -1 if it is missing.
  • Change it slightly: count the matches, find the first value over a limit, or return a true or false answer.
  • Trace it, or state its Big O and say why.

Our rubrics give a mark to each piece of the algorithm: the loop, the comparison, returning the index, and returning -1 at the right moment. That last one is the easiest to get wrong.

Key idea: A linear search checks each value in turn, from the start, and stops at the first match.

Watch it look

Here the search wants the first 7. Step through it and watch the arrow move along the list.

The search gives back a position, not a value. You already know the value (it is the target), so the useful answer is where it is.

As a function

Most questions want a function. A return inside the loop ends the function at once, so it does the job of break.

def linear_search(values, target):
    for i in range(len(values)):
        if values[i] == target:
            return i
    return -1


print(linear_search([12, 7, 19, 7, 3], 7))
print(linear_search([12, 7, 19, 7, 3], 5))
public static int linearSearch(int[] values,
                               int target) {
    for (int i = 0; i < values.length; i++) {
        if (values[i] == target) {
            return i;
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] scores = {12, 7, 19, 7, 3};
    System.out.println(
        linearSearch(scores, 7));
    System.out.println(
        linearSearch(scores, 5));
}

Both print 1, then -1. The return -1 sits after the loop, so it only runs when every value has been checked and none matched.

Key idea: Return -1 only after the loop has looked at every value.

The early -1

Here is the easiest slip to make. The else looks tidy, but it is in the wrong place.

def linear_search(values, target):
    for i in range(len(values)):
        if values[i] == target:
            return i
        else:
            return -1
    return -1

This version only ever looks at the first value. It still gives the right answer when the target is first or missing, which is why it can pass a quick test and still lose marks.

How it is marked

An exam-style question of our own, marked a point at a time. Switch to the second script for the early -1.

The same marks go to a Java answer, or to a version with a while loop and a found flag. Either works, as long as it stops at the first match and only says "not found" once it has looked everywhere.

How fast it is

For a list of n values, the best case is one comparison: the target is first. The worst case is n comparisons: the target is last, or missing. So a linear search is O(n). Double the list and, in the worst case, you double the work.

A linear search has one big strength: it works on any list, sorted or not. The next lesson's search is much faster, but only on sorted data.

Ready-made searches

Python's target in values and values.index(target) both do a linear search for you, so they are O(n) too. Note that index does not give -1 when the value is missing: it raises a ValueError, which stops the program unless it is caught. A question that says "construct" or "write" a search wants the loop, so write it out.

Now try it yourself on the questions below.

Exercise 7.5.17.5.1 · Write itWhere is it?

Write a function that does a linear search: it looks through a list (an array in Java) of whole numbers, from the start, for a target value.

  1. Return the index of the target, counting from 0.
  2. If the target is in the list more than once, return the index of the first one.
  3. If the target is not in the list, return -1.
  4. The list can be empty.

Do not use a ready-made search such as values.index(target) (indexOf in Java): write the loop. Only the value your function returns is checked.

def position_of(values: list[int], target: int) -> int

You cannot use these in this question:

  • .index()
  • import operator

This question is about writing the linear search yourself, so ready-made searches are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • position_of([4, 8, 15, 16], 15) should return 2: the target is in the middle (rule 1)
  • position_of([4, 8, 15, 16], 5) should return -1: the target is not there (rule 3)
  • position_of([3, 9, 3, 9], 9) should return 1: the target is there twice: the first one counts (rule 2)
  • position_of([9, 1, 2], 2) should return 2: the target is the last value (rule 1)

public static int positionOf(int[] values, int target)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Arrays.asList()
  • Arrays.binarySearch()
  • .indexOf()
  • .contains()

This question is about writing the linear search yourself, so ready-made searches are not allowed.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • positionOf(new int[]{4, 8, 15, 16}, 15) should return 2: the target is in the middle (rule 1)
  • positionOf(new int[]{4, 8, 15, 16}, 5) should return -1: the target is not there (rule 3)
  • positionOf(new int[]{3, 9, 3, 9}, 9) should return 1: the target is there twice: the first one counts (rule 2)
  • positionOf(new int[]{9, 1, 2}, 2) should return 2: the target is the last value (rule 1)
solution.pySolution.java

Exercise 7.5.27.5.2 · Write itFirst hot day

A weather station keeps one temperature a day, in whole degrees, in a list (an array in Java). Day 0 is the first day. Write a function that finds the first day that was hotter than a limit.

  1. Return the first day whose temperature is greater than limit.
  2. A temperature equal to the limit is not hotter than it.
  3. If no day was hotter, return -1.
  4. The list can be empty, and temperatures can be below zero.

Only the value your function returns is checked.

def first_day_over(temps: list[int], limit: int) -> int

Examples

Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.

  • first_day_over([21, 24, 31, 28, 33], 30) should return 2: day 2 is the first day over 30 (rule 1)
  • first_day_over([21, 24, 19], 30) should return -1: no day is over the limit (rule 3)
  • first_day_over([30, 30, 31], 30) should return 2: days equal to the limit do not count (rule 2)

public static int firstDayOver(int[] temps, int limit)

Checking whether Java answers can run here.

Examples

Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.

  • firstDayOver(new int[]{21, 24, 31, 28, 33}, 30) should return 2: day 2 is the first day over 30 (rule 1)
  • firstDayOver(new int[]{21, 24, 19}, 30) should return -1: no day is over the limit (rule 3)
  • firstDayOver(new int[]{30, 30, 31}, 30) should return 2: days equal to the limit do not count (rule 2)
solution.pySolution.java

Report a problem with this page