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
Using linear search determine the position of 8, 1, 99 and 44 in the list:
[1, -2, 32, 8, 17, 19, 42, 13, 0, 44]Draw a detailed table showing the values of the variables and the decisions taken in each pass of linear search.
Write a program that takes as input a list having a mix of 10 negative and positive numbers and a key value. Apply linear search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3 different keys and note the result.
Write a program that takes as input a list of 10 integers and a key value and applies binary search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3 different key values and note the results.
Following is a list of unsorted/unordered numbers:
[50, 31, 21, 28, 72, 41, 73, 93, 68, 43, 45, 78, 5, 17, 97, 71, 69, 61, 88, 75, 99, 44, 55, 9]- Use linear search to determine the position of 1, 5, 55 and 99 in the list. Also note the number of key comparisons required to find each of these numbers in the list.
- Use a Python function to sort/arrange the list in ascending order.
- Again, use linear search to determine the position of 1, 5, 55 and 99 in the list and note the number of key comparisons required to find these numbers in the list.
- Use binary search to determine the position of 1, 5, 55 and 99 in the sorted list. Record the number of iterations required in each case.