Standard searching algorithms: Linear search
2.1.3 Searching and sorting algorithms
Practise exam questionsSearching and sorting algorithms — Note 2 of 5
Understand the main steps of each algorithm, Understand any pre-requisites of an algorithm, Apply the algorithm to a data set, Identify an algorithm if given the code or pseudocode for it
Linear search is a simple searching algorithm that checks each item in a list one by one, starting from the first item, until the target is found or the end of the list is reached. It works on both sorted and unsorted lists, making it versatile but slower than binary search for large datasets.
False / -1 or 'not found'.found = False before the loop, set it to True when a match is found, then check it after the loop.theTeam[count].else: print("Not found") inside the loop prints 'Not found' once for every item that doesn't match. Only decide 'not found' AFTER every item has been checked.def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i # Found at index i
return -1 # Not found
numbers = [15, 7, 3, 5, 13, 8]
print(linear_search(numbers, 13)) # Output: 4
print(linear_search(numbers, 6)) # Output: -1scores = [12, 7, 5, 10, 3, 2, 7]
target = 7 # the value we are searching for
found = False # flag: nothing found yet
for i in range(len(scores)): # check each item IN ORDER
if scores[i] == target:
found = True # set the flag when a match is found
if found: # checked AFTER the loop
print("Found")
else:
print("Not found")Ready to test yourself?
Practise 2.1.3 questions