Signed up recently but had issues with the confirmation email?
Click Forgot password and follow the reset steps. You can choose the same password you used when you signed up. This should then provide access.
Remember to check Spam and Junk. The email will be from auth@progressbytes.co.uk.
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.function linearSearch(data, size, target)
for i = 0 to size - 1
if data[i] == target then
return i // found at index i
endif
next i
return -1 // not found
endfunction
array numbers = [15, 7, 3, 5, 13, 8]
print(linearSearch(numbers, 6, 13)) // outputs 4
print(linearSearch(numbers, 6, 6)) // outputs -1def 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: -1array scores = [12, 7, 5, 10, 3, 2, 7]
target = 7 // the value we are searching for
found = False // flag: nothing found yet
for i = 0 to 6 // check each item IN ORDER (7 items: indexes 0 to 6)
if scores[i] == target then
found = True // set the flag when a match is found
endif
next i
if found == True then // checked AFTER the loop
print("Found")
else
print("Not found")
endif
// this version checks every item; a version that stops at the first match uses a while loop or returns from a functionscores = [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")prices[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.Ready to test yourself?
Practise 2.1.3 questions