Linear Search is the simplest way of searching key element from the list of elements. In linear search the order of elements can be in ascending order or can be in descending order. The elements in the list can be redundant. Time complexity of this search is O(n).
Source Code:
a=[]
count=0
n=int(input("how many elements u want to enter"))
for i in range(n):
num=int(input("enter number"))
a.append(num)
print(a)
key=int(input("enter the key to be serched"))
for i in range(n):
if key==a[i]:
print("%d found in %d" %(key,i))
count=count+1
if count==0:
print("%d not found" %key)
else:
print("%d found %d time(s)" %(key,count))
Source Code:
a=[]
count=0
n=int(input("how many elements u want to enter"))
for i in range(n):
num=int(input("enter number"))
a.append(num)
print(a)
key=int(input("enter the key to be serched"))
for i in range(n):
if key==a[i]:
print("%d found in %d" %(key,i))
count=count+1
if count==0:
print("%d not found" %key)
else:
print("%d found %d time(s)" %(key,count))
Output:
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
how many elements u want to enter6
enter number1
enter number2
enter number3
enter number4
enter number5
enter number6
[1, 2, 3, 4, 5, 6]
enter the key to be serched3
3 found in 2
3 found 1 time(s)
>>> ================================ RESTART ================================
>>>
how many elements u want to enter6
enter number1
enter number2
enter number3
enter number3
enter number4
enter number5
[1, 2, 3, 3, 4, 5]
enter the key to be serched3
3 found in 2
3 found in 3
3 found 2 time(s)
>>>
No comments:
Post a Comment