Created
March 12, 2019 17:16
-
-
Save gozeloglu/5899446f1c4f36c53aaa3cab323afe03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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