Lesson 7.5 · Write it
Where is it?
A functionPython or Java11 tests, 7 of them hidden
On a phone? Put the lines in order instead
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.
- Return the index of the target, counting from 0.
- If the target is in the list more than once, return the index of the first one.
- If the target is not in the list, return
-1. - 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)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.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)