Complexity and efficiency · 7 / 15 Exercise Medium

Linear search counting steps

Objective

Create a Python program that performs a linear search in a list and counts how many comparisons it needs. In the worst case it is O(n): every element has to be checked.

Instructions

  • Read a line with integers separated by spaces and then a line with the integer to search for.
  • Go through the list from left to right, adding 1 to the comparison counter for each element, and stop as soon as you find it.
  • Show Position: i with the first position (starting at 0) or Not found, and then Comparisons: k.
Input
4 8 15 16 23 42
16
Output
Position: 3
Comparisons: 4

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise