Advertisement
HJ50

linear_search

Apr 6th, 2020
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. #linear search
  2.  
  3. def linear_search(looking_for, sequence, sorted):
  4.     index=-1
  5.     for i, val in enumerate(sequence):
  6.         if sorted:              #operating on sorted list
  7.             if val>looking_for: #don't bother looking any further
  8.                 print(val)      #for debug
  9.                 break
  10.         if val==looking_for:
  11.             index=i
  12.             break               #stop at first match
  13.     return index        
  14.        
  15.    
  16.  
  17. #test
  18. array=[2,5,4,6,7,4,5,6,8,2]
  19. sorted_array=[1,2,3,4,5,7,8,9,10]           #6 missing for test purposes
  20. print(linear_search(7,array, False))
  21. print(linear_search(6,sorted_array, True))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement