# Linear Search using MATLAB

• It is one of the simplest searching algorithm.
• A search algorithmis an algorithm that retrieves information stored within some data structure.
• It relies on the technique of traversing a list from start to end by exploring properties of all the elements that are found on the way.
• It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched
• The main advantage of this searching technique is its simplicity.
• Linear search is usually very simple to implement, and is practical when the list has only a few elements, or when performing a single search
• Time Complexity:
• Best Case : O(1)
• Average Case : O(n/2)
• Worst Case : O(n)
• So time complexity of linear searching is O(n).

# Example

We take an unsorted array for our example.

 15 11 6 4 1

# Best Case

Problem:  Search for Element 15 in given array

 15 11 6 4 1

1. Element 15 found at index 1

15=15

Print Index

# Average Case

Problem:  Search for Element 6 in given array

 15 11 6 4 1

1. Check Index 1
 15 11 6 4 1

Since 15 ≠ 6

Index=Index+1

1. Check Index 2
 15 11 6 4 1

Since 11 ≠ 6

Index=Index+1

1. Check Index 3
 15 11 6 4 1

Since 6= 6

Print Index

# Worst Case

Problem:  Search for Element 2 in given array

 15 11 6 4 1

1. Check Index 1
 15 11 6 4 1

Since 15 ≠ 2

Index=Index+1

1. Check Index 2
 15 11 6 4 1

Since 11 ≠ 2

Index=Index+1

1. Check Index 3
 15 11 6 4 1

Since 6 ≠ 2

Index=Index+1

1. Check Index 4
 15 11 6 4 1

Since 4 ≠ 2

Index=Index+1

1. Check Index 5
 15 11 6 4 1

Since 1 ≠ 2

Index=Index+1

1. Since Index is now out of bounds

# Pseudo-Code

for(start to end of array)

{

if (current_element equals to 5)

{

print (current_index);

}

}

# MATLAB Code

```
function [ index ] = Linear_Search(arr,find,l,r)

%arr   : Array of Elements
%find  : Element to be found
%l     : Left/Start index
%r     : Right/End index
%index : Answer array of all indexes where arr(index)==find

jj=1;
index=[];
for ii=l:r
if(arr(ii)==find)
index(jj)=ii;
jj=jj+1;
end
end

end

```

# Output

arr=[5 23 7 34 90 23 11];

Linear_Search(arr,23,1,7)

ans =

2     6

Linear_Search(arr,11,1,7)

ans =

7

Linear_Search(arr,91,1,7)

ans =

[]
##### Anushi Maheshwari

Anushi is pursuing graduation degree in Electronics & Communication from HBTI, Kanpur (Now HBTU). She has a keen interest towards Competitive Programming & loves to solve coding Challenges.

### Recommended Posts

##### Test Post

17 Feb 2018 - Tutorial

##### Counters using conditionally executed subsystems | Simulink Tutorial

16 Feb 2018 - Simulink, Tutorial

##### Regulating drum boiler pressure

16 Feb 2018 - Simulink, Tutorial