A linear search is used to check if a value is in an array. There are two ways of doing this:-
Check every value in the list, even if you find the value immediatly.
1 2 3 4 5 6 7 | def linSearchV1(target,numbers): #Search for target in all of the numbers found = False for counter in range ( len (numbers)): if numbers[counter] = = target: found = True return found |
Check until you find the value you are looking for, this is much more effient and can on average half the ammount of time taken for the program to run.
1 2 3 4 5 6 7 8 9 10 | def linSearchV2(target,numbers): #Search for the target numbers until it is found counter = 0 found = False while not found and counter! = len (numbers): if numbers[counter] = = target: found = True else : counter = counter + 1 return found |
The same algorithms can be used to find a string in an array of strings or a character in a string.