xxxxxxxxxx
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = [1,2,3,4,5,6,7,8]
x = 4
print("element found at index "+str(linearsearch(arr,x)))
xxxxxxxxxx
def linear_search(a, key):
position = 0
flag = False
while position < len(a) and not flag:
if a[position] == key:
flag = True
else:
position = position + 1
return flag
xxxxxxxxxx
arr = [100, 200, 300, 400, 500]
x = 400
def search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
print(search(arr, x))
xxxxxxxxxx
#this is really basic, but it'll do
Array = [1,2,3,4,5,6,7,8] #example array
def LinearSearch(Array, SearchVal): #SearchVal= value you are looking for
for i in range(len(Array)):
if Array[i]== SearchVal:
return True
return False
#once it has looped through all of the array and hasn't found
#the search value, it will return False.
xxxxxxxxxx
def locate_card(cards, query):
# Create a variable position with the value 0
position = 0
# Set up a loop for repetition
while True:
# Check if element at the current position matche the query
if cards[position] == query:
# Answer found! Return and exit..
return position
# Increment the position
position += 1
# Check if we have reached the end of the array
if position == len(cards):
# Number not found, return -1
return -1
xxxxxxxxxx
# Linear Search:
"""
Another classic example of a brute force algorithm is Linear Search.
This involves checking each item in a collection to see if it is the
one we are looking for.
In Python, it can be implemented like this:
"""
arr = [42,2,3,1,4,6]
search_n = 2
for position, item in enumerate(arr):
if item == search_n:
print("%d The searching number is at position %d inside the array."%(search_n,position+1))
break
else:
print("Sorry! Not Found.")
"""
Of course there are many different implementations of this algorithm.
I like this one because it makes use of Python’s very handy enumerate function.
Regardless of the details of the implementation,
the basic idea remains the same – iterate through the collection (in the case above, a Python list),
and check if each item is the target.I like to use the variable names search_n and array from the
expression looking for a search_n in a array.
"""
xxxxxxxxxx
def linear_search(lists, word):
for i in range(len(lists)):
if lists[i] == word:
return True
return False
A = [12, 34, 19, 43, 56, 12, 99, 23, 19, 26, 29, 56, 78, 53]
word = 4
index = A.index(word)
if linear_search(A, word):
print(f"Found at index {index}")
else:
print("Element Not Found")
xxxxxxxxxx
def LinearSearch(input_list: list, element: int):
list_len = len(input_list)
for i in range(list_len):
if input_list[i] == element:
return i
return -1
myList = [1, 23, 45, 23, 34, 56, 12, 45, 67, 24]
print("Given list is:", myList)
position = LinearSearch(myList, 12)
print("Element 12 is at position:", position)