Searching & max / min
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Linear search
- A linear search looks at each item in turn until it finds the target.
- It is a named standard method in the syllabus.
- Use a loop and remember when you find a match.
nums = [4, 9, 2, 7]
target = 9
found = False
for n in nums:
if n == target:
found = True
print(found) # True
Explore
Linear search, step by step
A linear search checks each item in turn until it finds the target.
Finding the maximum
- Start by assuming the first item is the biggest.
- Then check the rest; if one is bigger, remember it instead.
nums = [4, 9, 2, 7]
biggest = nums[0]
for n in nums:
if n > biggest:
biggest = n
print(biggest) # 9
Finding the minimum
- The same idea, but keep the smallest value seen so far.
nums = [4, 9, 2, 7]
smallest = nums[0]
for n in nums:
if n < smallest:
smallest = n
print(smallest) # 2
In the exam: standard methods
- Linear search and finding maximum / minimum / average are named in section 7.
Found ← FALSE
FOR i ← 1 TO 4
IF Number[i] = Target THEN
Found ← TRUE
ENDIF
NEXT i
Common mistakes
- Linear search checks each item in turn until it finds the target.
- For max or min, start from the first item, then compare the rest against it.
Now you try
- Loop through the list to search or compare.
- Press Check answer to test your code.
Write contains(nums, target) that returns True if target is in the list, using a linear search loop (do not use the in keyword).
Click Run to see the output here.
The list nums is set. Find the largest value with a loop and store it in biggest (do not use max()).
Click Run to see the output here.
Find the smallest value in nums with a loop and store it in smallest (do not use min()).
Click Run to see the output here.