Skip to content

Instantly share code, notes, and snippets.

@gozeloglu
Created March 12, 2019 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gozeloglu/5899446f1c4f36c53aaa3cab323afe03 to your computer and use it in GitHub Desktop.
Save gozeloglu/5899446f1c4f36c53aaa3cab323afe03 to your computer and use it in GitHub Desktop.
import random as rd
""" This is the simplest searching algorithm.
All elements checked in data one by one.
If value is found in array, its index is returned.
If not found, function returns -1.
Complexity of this algorithm is O(n)
In the best case scenerio, value can be found in first
index.
In the worst case scenirio, value is found in last index"""
def linear_search(arr, value):
for i in range(len(arr)):
if arr[i] == value:
return i
return -1
# Test
for i in range(10):
arr = [rd.randint(1, 30) for _ in range(20)]
value = i
ind = linear_search(arr, value)
print(" ".join(list(map(str, arr))), end=" ---> ")
if ind != -1:
print(value, " found in ", ind)
else:
print(value, " not found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment