Unit 5 · Data and algorithms
Why your search gives up after one item
A return inside the loop ends the whole function. Put return -1 after the loop, so it only runs once every item has been checked and none matched.
The mix-up
What people often think
“If the first card is not a match, the target is not there.”
What the tutor says
Returning -1 inside the loop stops after one card. Only return -1 after the loop has checked every item.
Where does the code go after the last card has been checked?
How it works
One item not matching proves nothing about the rest. Return early only when you find the target; the “not found” answer belongs after the loop.
Start the loop at i = 0, or the first item is never checked. And always return something when nothing is found, so the caller can tell the difference.
Side by side
for (let i = 0; i < list.length; i++) {
if (list[i] === target) return i;
else return -1; // gives up after one
}for (let i = 0; i < list.length; i++) {
if (list[i] === target) return i;
}
return -1; // checked them allClose cousins of this mix-up
The tutor watches for these in the same lesson.
“The target will always be in the list.”
Searches often come up empty. After the loop, return -1 so the caller knows nothing was found.
“A loop over a list starts at 1.”
Start at i = 0, or you skip the first item. That is why the check for index 0 fails.
Practise it with a tutor watching
Search
Write a linear search and explain when binary search is allowed and why it wins.
Free with an account. The first two units need no account.