Linear Search
CT04d
- Apply a linear search to a one-dimensional list (paper)
- Complete a linear search algorithm in a flowchart
- Write a linear search for a single item in a one-dimensional list (code).
Searching for information
CT04d
Take a look at this set of data.
You need to find a specific value.
How would you (as a person) go about doing this?
How would you program a computer to do it?
Input
CT04d
As you study Computer Science, you’ll find that many problems you encounter have already been solved.
For example, as computing has developed, a number of searching and sorting algorithms have been produced. You’ll learn about a few of them throughout this course.
The first, and probably the most intuitive to use, is the linear search algorithm.
Linear search characteristics
CT04d
The linear search provides a logical search solution. It’s simple to understand and to implement in code.
It’s not the most efficient algorithm, but you’ll learn about alternatives that perform more effectively in future lessons.
Linear search algorithm
CT04d
A linear search algorithm looks at each item in a data set (a list or array) in turn and compares it against a specified desired value.
If the item matches, information about that value is returned, such as the value itself, its position in the list, or a message.
If it does not match, the algorithm moves on to the next item in the data set and continues comparing.
If the algorithm reaches the end of the data set without finding the desired value, it returns an indication that the item has not been found.
Can you think of a numeric value that could indicate when an item is not found in the data set?
Flowchart
CT04d
Increment means ‘add one to’.
If the index is the same as length of the list, the program’s reached the end.
Dry run
CT04d
Doing a dry run means executing an algorithm as if you are a computer.
The tricky bit is to not think like a person, but to follow the algorithm exactly like a computer would.
In the lesson activities, you’re going to follow algorithms.
Go step by step, slowly, and don’t skip steps.
Activity 1a
CT04d
Here is a one-dimensional array of the last names of female athletes.
athlete = ["Persoon", "Bopp", "Hammer", "Serrano", "Kom", "Akar"]
Here is the flowchart for the linear search algorithm.
Dry run the linear search algorithm for target = ‘Serrano’. Answer these questions as you dry run.
- What is the value of ‘len(list)’?
- What is the first value of ‘index’?
- What is the final value of ‘index’?
- What is the value returned?
- What does the returned value mean?
Activity 1a
CT04d
athlete = ["Persoon", "Bopp", "Hammer", "Serrano", "Kom", "Akar"]
- What is the value of ‘len(list)’?
- What is the first value of ‘index’?
- What is the final value of ‘index’?
- What is the value returned?
- What does the returned value mean?
Activity 1a
CT04d
athlete = ["Persoon", "Bopp", "Hammer", "Serrano", "Kom", "Akar"]
- What is the value of ‘len(list)’? 6
- What is the first value of ‘index’? 0
- What is the final value of ‘index’? 3
- What is the value returned? 3
- What does the returned value mean?
The location of ‘Serrano’ in the list.
Activity 1b
CT04d
athlete = ["Persoon", "Bopp", "Hammer", "Serrano", "Kom", "Akar"]
Dry run the linear search algorithm for target = ‘Castillo’. Answer these questions as you dry run.
- List all the values of ‘index’ as they change.
- What is the final value of ‘index’?
- What does the final value of ‘index’ represent?
- What is the value returned?
- What does the returned value mean?
Activity 1b
CT04d
athlete = ["Persoon", "Bopp", "Hammer", "Serrano", "Kom", "Akar"]
Dry run the linear search algorithm for target = ‘Castillo’. Answer these questions as you dry run.
- List all the values of ‘index’ as they change.
0 1 2 3 4 5 6 - What is the final value of ‘index’? 6
- What does the final value of ‘index’ represent?
The length of the list.
- What is the value returned? -1
- What does the returned value mean?
The value ‘Castillo’ is not in the list.
Linear search (code)
CT04d
Algorithms in flowcharts can be translated into program code.
Remember that they are not always translated exactly.
Let’s look at some code for a linear search.
Activity 2
CT04d
Load ‘Activity2_Student.py’ into your development environment. The code for the subprogram ‘linearSearch’ is all jumbled up.
Arrange the code to make a functional program. Comments on the lines will help you.
The main program does not need to be changed. You can use it for testing.
def linearSearch (pTarget, pList):
# -----> These lines are all jumbled up
index = 0
index = -1
moreItems = True # Assume you have items
moreItems = False
found = False # Assume not found yet
found = True
index = index + 1 # Check if all items seen
return (index)
while ((not found) and (moreItems)):
else: # It is the target, stop loop
if (index == len(pList)): # No more, stop loop, return invalid
if (pList[index] != pTarget): # Not this one, so go forward
Activity 2
CT04d
Arrange the code to make a functional program. Comments on the lines will help you.
def linearSearch (pTarget, pList):
# -----> These lines are all jumbled up
index = 0
moreItems = True # Assume you have items
found = False # Assume not found yet
while ((not found) and (moreItems)):
if (pList[index] != pTarget): # Not this one, so go forward
index = index + 1 # Check if all items seen
if (index == len(pList)): # No more, stop loop, return invalid
moreItems = False
index = -1
else: # It is the target, stop loop
found = True
return (index)
While vs For
CT04d
You might have noticed that in Activity 1 the code you were given used a ‘while loop’.
Previously you have used a ‘for loop’ to iterate over a list.
However, a ‘for loop’ iterates over a whole list from start to finish without stopping.
This would make the program in Activity 1 inefficient as you need the loop to stop once the item has been found.
Using a ‘for loop’ would not allow this to happen properly, so, in applications like this, a ‘while loop’ is much more effective.
Activity 3
CT04d
Load ‘Activity3_Student.py’ into your development environment. The linear search subprogram has code missing.
Complete the code to make a functional program.
The main program does not need to be changed. You can use it for testing.
def linearSearch (inList, inTarget):
index = 0
moreItems =
found =
while ():
if ( != ):
index = index + 1
if (index == ):
moreItems = False
index = -1
else:
found = True
return (index)
Activity 3
CT04d
Load ‘Activity3_Student.py’ into your development environment. The linear search subprogram has code missing.
Complete the code to make a functional program.
The main program does not need to be changed. You can use it for testing.
def linearSearch (inList, inTarget):
index = 0
moreItems = True
found = False
while ((not found) and (moreItems)):
if (inList[index] != inTarget):
index = index + 1
if (index == len(inList)):
moreItems = False
index = -1
else:
found = True
return (index)
Activity 4
CT04d
Load ‘Activity4_Student.py’ into your development environment. The linear search subprogram needs to be completed. There are comments in the code. You must complete the code by adding one or two lines under each comment. Debug and test your program to ensure it functions properly.
The main program does not need to be changed. You can use it for testing.
# -----> Create a subprogram header with parameters for the
# list and the target
index = 0
# -----> Create and initialise a variable to indicate end of list
# -----> Create and initialise a variable to indicate found or not
# -----> Create an outside while loop that keeps going if there
# are more elements and the target is not found
# -----> Use an if to check if current matches target
# -----> Increment current location
# -----> Use an if to check if found end of list
# -----> Stop loop (two lines)
# -----> Use an else to handle target found (2 lines)
# -----> Give back the position
Activity 4
CT04d
# -----> Create a subprogram header with parameters for the
# list and the target
index = 0
# -----> Create and initialise a variable to indicate end of list
# -----> Create and initialise a variable to indicate found or not
# -----> Create an outside while loop that keeps going if there
# are more elements and the target is not found
# -----> Use an if to check if current matches target
# -----> Increment current location
# -----> Use an if to check if found end of list
# -----> Stop loop (two lines)
# -----> Use an else to handle target found (2 lines)
# -----> Give back the position
CT04d
def linearSearch (pTarget, pList):
index = 0
# -----> Create and initialise a variable to indicate end of list
moreItems = True # Assume you have items
# -----> Create and initialise a variable to indicate found or not
found = False # Assume not found yet
# -----> Create an outside while loop that keeps going if there
# are more elements and the target is not found
while ((not found) and (moreItems)):
# -----> Use an if to check if current matches target
if (pList[index] != pTarget): # Not this one, so go forward
# -----> Increment current location
index = index + 1 # Check if all items seen
# -----> Use an if to check if found end of list
if (index == len(pList)): # No more, stop loop, return invalid
# -----> Stop loop (two lines)
moreItems = False
index = -1
# -----> Use an else to handle target found (2 lines)
else: # It is the target, stop loop
found = True
# -----> Give back the position
return (index)
Review
CT04d
Apply a linear search to a one-dimensional list (paper).
- Look at each item in turn until you find the one you want.
- This is the most ‘human friendly’ algorithm as it’s the most similar to how we naturally search for things
Complete a linear search algorithm in a flowchart.
- Use a loop with a decision to check if the current item matches the target.
- Check for the end of the list.
Write a linear search for a single item in a one-dimensional list (code).
- Use a while loop so that you can stop as soon as you find the value needed. This makes the code more efficient.
ct04d Linear Search
By David James
ct04d Linear Search
- 476