Linear search example
The linear search is used to find an item in a list.
The items do not have to be in order.
To search for an item, start at the beginning of the list and continue searching until either the end of the list is reached or the item is found.
#simple program to explain linear search by using funcion
#defining the function
def linearsearch(list,s_element):
for i in range(0,len(list)):
if list[i]==s_element:
return i
return -1
#defining any list with elements
alist=[12,5,3,0,8]
#displaying the list
print(alist)
#accepting element from user to search
se=int(input("enter element to search:"))
#defining variable to store the result of linear search
loc=linearsearch(alist,se)
#displaying the result
if loc==-1:
print("element is not in a list")
else:
print("index of element in list:",loc)
OUTPUT :
The linear search is used to find an item in a list.
The items do not have to be in order.
To search for an item, start at the beginning of the list and continue searching until either the end of the list is reached or the item is found.
#simple program to explain linear search by using funcion
#defining the function
def linearsearch(list,s_element):
for i in range(0,len(list)):
if list[i]==s_element:
return i
return -1
#defining any list with elements
alist=[12,5,3,0,8]
#displaying the list
print(alist)
#accepting element from user to search
se=int(input("enter element to search:"))
#defining variable to store the result of linear search
loc=linearsearch(alist,se)
#displaying the result
if loc==-1:
print("element is not in a list")
else:
print("index of element in list:",loc)
OUTPUT :