Reputation:
I wrote a program for linear search in python but it doesn's work correctly.
I tried double checking the program but I couldn't find the mistake.
def LinearSearch(arr, n):
for i in arr:
if i == n:
return i
else:
return -1
def main():
arr1 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
n1 = 110
arr2 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
n2 = 175
result1 = LinearSearch(arr1, n1)
if result1 == n1:
print('Item %d found at index %d' % (n1, result1))
else:
print('Item not found')
result2 = LinearSearch(arr2, n2)
if result2 == n2:
print('Item %d found at index %d' % (n2, result2))
else:
print('Item not found')
main()
I expected output 'Element x is present at index 6' for the first search but it says 'Item not found'.
Upvotes: 1
Views: 52
Reputation: 13551
Since your LinearSearch
function always met the return
for any case and the function is just ended when it met return
without looping. Thus, the function only gives -1
because the first element for each list is 10
which is not matching with 110
and 175
.
Here is my modification.
def LinearSearch(arr, n):
count = 0
for i in arr:
if i == n: return count
else: count += 1
return -1
def main():
arr1 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
n1 = 110
arr2 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
n2 = 175
result1 = LinearSearch(arr1, n1)
if result1 != -1: print('Item %d found at index %d' % (n1, result1))
else: print('Item not found')
result2 = LinearSearch(arr2, n2)
if result2 != -1: print('Item %d found at index %d' % (n2, result2))
else: print('Item not found')
main()
Upvotes: 2