2. List of contents
● Introduction
● Example w/ illustrating figures
● Algorithm
● implementation (Java, C++, Python)
● Performance Runtime
○ Best, Average and worst cases.
● Execution
● Other Notes
3. Introduction
● Problem : Given an array arr[] of n elements, write a function to search a given element
x in arr[] .
● Linear search is the simplest but most timfull algorithm to find an element .
5. Algorithm .
● Start from the leftmost element of arr[] and one by one compare x with each element of
arr[]
● If “x” matches with an element, return the index.
● If “x” doesn’t match with any of elements, return -1.
6. Implementation .
int linearSearch(int arr[], int n, int x)
{
for (int i=0; i<n; i++)
if (arr[i] == x)
return i ;
return -1;
}
//for java add static .
C++ / JAVA
def linearSearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
PYTHON
7. Performance Runtime
● Time complexity Θ(n) .
● Best case : when the element is at first index .
● Average case : if it exists between first to last .
● Worst case : if the element doesn’t exist .
8. Execution .
Input array : [4, 6, 3, 2, 1, 9, 7]
Find 2 .
if(4 == 2) no
if(6 == 2) no
if(3 == 2) no
if(2 == 2) return 3
Element exists at index 3.
9. Other Notes .
● Algorithmic Paradigm: Linear Approach
● Stable: Yes
● Linear search is rarely used practically because other search algorithms such as the binary
search algorithm and hash tables allow significantly faster searching comparison to Linear
search.