Skip to content

Commit 5f69f7c

Browse files
authored
Added linear search in python
1 parent 8af0886 commit 5f69f7c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Searching Algorithms/linear_search.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#Linear Search in python
2+
#Linear Search is one of the easiest searching algorithm. The main aim of a searching algorithm is to search for a desired element in the whole array. Linear Search sequentially searches for an element in an array.
3+
#algorithm
4+
#In Linear Search, we start from the 0th index of the array, we compare each element with the key (desired element).
5+
#If the key is same as the element of array ,we return the index of that element.
6+
#If the key does not match any element then ,we return -1.
7+
def search(arr, x):
8+
for i in range(len(arr)):
9+
if arr[i] == x:
10+
return i
11+
return -1
12+
13+
14+
n=int(input("Enter Size of array: "))
15+
arr=[]
16+
print("Enter array elements: ")
17+
for i in range(n):
18+
e=int(input())
19+
arr.append(e)
20+
x=int(input("Enter element to be searched: "))
21+
ans=search(arr,x)
22+
if ans==-1:
23+
print("Element not found ")
24+
else:
25+
print("Element found at ",ans)
26+

0 commit comments

Comments
 (0)