Linear Search Flashcards

1
Q

How it works?

A
  1. Go through the array value by value from the start.
  2. Compare each value to check if it is equal to the value we are looking for.
  3. If the value is found, return the index of that value.
  4. If the end of the array is reached and the value is not found, return -1 to indicate that the value was not found.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Big O (Time Complexity)?

A

O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly