Computer Science

Use the linear search program to search the key with value 8 in the list having duplicate values such as [42, -2, 32, 8, 17, 19, 42, 13, 8, 44]. What is the position returned? What does this mean?

Python Searching

5 Likes

Answer

def linear_search(lst, key):
    position = -1  
    for i in range(len(lst)):
        if lst[i] == key:
            position = i 
            break  
    return position

lst = [42, -2, 32, 8, 17, 19, 42, 13, 8, 44]
key = 8
result = linear_search(lst, key)

if result != -1:
    print("The position of key", key, "in the list is", result)
else:
    print("Key", key, "not found in the list.")
Output
The position of key 8 in the list is 3

It will return the index 3 (position 4) for the value 8, because at this index first 8 is encountered. Simple linear search returns the index of first successful match.

Answered By

1 Like


Related Questions