Skip to content

Commit a064e09

Browse files
committed
Linear searching code added
1 parent 4884b8e commit a064e09

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

Searching/Linear Search/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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](http://stackoverflow.com/a/7571665/4230330) by:
11+
12+
`item in list`
13+
14+
and [finding an item's index](http://stackoverflow.com/a/176921/4230330) 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+
25+
26+
### More on this topic
27+
- https://en.wikipedia.org/wiki/Linear_search
28+
- https://www.tutorialspoint.com/data_structures_algorithms/linear_search_algorithm.htm
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//Linear Search implementation
2+
function linearSearch(arr, item){
3+
var len = arr.length;
4+
for(var i=0; i<len; i++){
5+
if(item === arr[i])
6+
return true; //You can also return the index from here
7+
}
8+
9+
return false;
10+
}
11+
12+
13+
//Testing Linear Search implementation
14+
var hayStack = ['book','pencil','pen','note book','sharpener','rubber']
15+
var needle = 'note book';
16+
17+
console.log(linearSearch(hayStack, 'note book'));
18+
console.log(linearSearch(hayStack, 'dog'));
36.7 KB
Loading

0 commit comments

Comments
 (0)