Linear search
Look at each item in turn until you find the one you want or reach the end. The items can be in any order.
Simple example
Look for 3. Check 8 first, then 3. Print the position counting from one.
Start8 3 5
Result2
values = [8, 3, 5]
i = 0
while i < 3
if values[i] == 3
puts i + 1
break
end
i += 1
end
2
Advertisements
Everyday examples
Find an unlabelled shelf position
Books arrive in the order 8, 3, 5. Where is book 5?
Start8 3 5
Result3
Check each spine. The third book matches.
Call the first volunteer
Two volunteers share the name May. Which one is called if you stop at the first match?
StartAnn May May
Result2
Walk down the list in order and stop at the earlier May.
Check a missing parcel
A van carries parcels 7 and 9. A customer asks for 8. When can you say it is missing?
Start7 9
Result∅
Check both parcels. An early mismatch does not rule out a later match.
Cost and limits
A first match can take one check. A missing item requires checking all n items.