You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers the linear search algorithm as required by OCR J277 Section 2.2. Linear search is one of the standard searching algorithms you must know for the OCR GCSE Computer Science exam, and you need to be able to describe how it works, write it in pseudocode or a programming language, and trace through it using a trace table.
Linear search (also called sequential search) is the simplest searching algorithm. It works by checking each item in a list, one at a time, from the first element to the last, until the target item is found or the end of the list is reached.
Think of it like looking for a specific book on a shelf by checking every book from left to right, one by one.
function linearSearch(list, target)
for i = 0 to list.length - 1
if list[i] == target then
return i
endif
next i
return -1
endfunction
A return value of -1 indicates the item was not found.
def linear_search(lst, target):
for i in range(len(lst)):
if lst[i] == target:
return i
return -1
# Example usage
numbers = [5, 3, 8, 1, 9, 2, 7]
result = linear_search(numbers, 9)
if result != -1:
print("Found at index", result)
else:
print("Not found")
OCR Exam Tip: When writing search algorithms in pseudocode, always use the OCR convention of
for i = 0 to n ... next ifor loops. The examiner wants to see you follow the OCR pseudocode reference language.
Let us trace through searching for the value 7 in the list [4, 2, 7, 1, 9]:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.