Skip to content

Commit 70f42b0

Browse files
committed
linear search code and readme added
1 parent dde29ce commit 70f42b0

File tree

4 files changed

+43
-0
lines changed

4 files changed

+43
-0
lines changed

Searching/Linear Search/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Linear Search
2+
3+
**Linear search** is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
4+
5+
![Linear Search](Linear_search.gif)
6+
7+
8+
#### Python Implementation
9+
10+
Though it is very easy in python to check for an item's existence in a list by:
11+
12+
`item in list`
13+
14+
and finding an item's index by:
15+
16+
`list.index(item)`
17+
18+
but sometimes you might need to do some customization on the searching algorithm. Like- *'finding the last occurrence of the item in the list'* etc. This linear search implementation will help you to do that.
19+
20+
#### Complexity Analysis
21+
- Worst Case - O(n)
22+
- Best Case - O(1)
23+
- Average Case - O(n)
24+
- Space Complexity - O(n)
25+
26+
27+
### More on this topic
28+
- https://en.wikipedia.org/wiki/Linear_search
29+
- https://www.tutorialspoint.com/data_structures_algorithms/linear_search_algorithm.htm
36.7 KB
Loading

Searching/Linear Search/search.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def linearSearch(item, item_list):
2+
for index, val in enumerate(item_list):
3+
if val == item:
4+
return True #You can return the index of the found element by 'return index'
5+
return False

Searching/Linear Search/test.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from search import linearSearch
2+
3+
hayStack = ['book','pencil','pen','note book','sharpener','rubber']
4+
needle = input('What do you want to find: ')
5+
6+
if linearSearch(needle, hayStack):
7+
print('Found')
8+
else:
9+
print('Not Found')

0 commit comments

Comments
 (0)