Linear Search Flashcards
1
Q
How it works?
A
- Go through the array value by value from the start.
- Compare each value to check if it is equal to the value we are looking for.
- If the value is found, return the index of that value.
- If the end of the array is reached and the value is not found, return -1 to indicate that the value was not found.
2
Q
Code?
A
def linearSearch(arr, targetVal): for i in range(len(arr)): if arr[i] == targetVal: return i return -1 arr = [3, 7, 2, 9, 5] targetVal = 9 result = linearSearch(arr, targetVal) if result != -1: print("Value",targetVal,"found at index",result) else: print("Value",targetVal,"not found")
3
Q
Big O (Time Complexity)?
A
O(n)