Comments

Notes

MCS 211

18 topics

Linear Search

Updated Feb 03, 20252 min read

​Linear search or sequential search is a very simple search algorithm which isused to search for a particular element in an array. Unlike binary searchalgorithm, in linear search algorithm, elements are not arranged in a particularorder. In this type of search, an element is searched in an array sequentiallyone by one. If a match is found then that particular item is returned and thesearch process stops. Otherwise, the search continues till the end of an array.The following steps are used in the linear search algorithm:

How Linear Search Works

​Linear_ Search( A[ ], X)

Step 1: Initialize i to 1

Step 2: if i exceeds the end of an array then print “element not found” and Exit

Step 3: if A[i] = X then Print “Element X Found at index i in the array” and Exit

Step 4: Increment i and go to Step 2

Algorithm Steps

Initialize:
Start at the beginning of the list (index 0).

Iterate through the List:

  • For each element in the list:
    • Compare the current element with the target value.
    • If the element equals the target, return the index (or the element itself, depending on the requirements).

Termination:

  • If the target is found, the search stops.
  • If the end of the list is reached without finding the target, the algorithm indicates that the target is not present (often by returning -1 or null).

Pseudocode

​function linearSearch(array, target):
for index from 0 to length(array) - 1:
if array[index] == target:
return index // Target found at this index
return -1 // Target not found



Time and Space Complexity

​Time Complexity:

Case
Best Case 
Worst Case
Average Case
Item is Present
O(1)
O(n)
O(n/2) = O(n)
Item is not Present
O(n)
O(n)
O(n)


Space Complexity:

​O(1) — Only a constant amount of extra memory is needed regardless of the size of the input.​


Share