Skip to content

Commit 51867c9

Browse files
committed
Linear Search
1 parent a538c43 commit 51867c9

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

Searching-Algo/linearsearch.py

+17-6
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,23 @@
22
Linear Search
33
Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In Linear search, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL.
44
'''
5-
6-
def linearsearch(n,t):
7-
for i in range(len(n)):
8-
if t==n[i]:
5+
#iterative approach
6+
def linearsearch(list,target):
7+
for i in range(len(list)):
8+
if target==list[i]:
99
return i
1010
return -1
1111

12-
a = [1,2,4,5,8]
13-
print(linearsearch(a,8)) #4
12+
list = [1,2,4,5,8]
13+
print(linearsearch(list,8)) #4
14+
15+
#recursive approach
16+
def linearsearch(list,curr_index,target):
17+
if curr_index == -1:
18+
return -1
19+
if list[curr_index] == target:
20+
return curr_index
21+
return linearsearch(list, curr_index-1,target)
22+
23+
list = [1,2,4,5,8]
24+
print(linearsearch(list,len(list)-1,8)) #4

0 commit comments

Comments
 (0)