In this chapter we shall learn about below topics:
1.1 Introduction
1.2 Understanding Linear Search with an example
1.3 Implementation of Linear Search in C
1.4 Output of the program
1.5 Time complexity of Linear Search
1.1 Introduction:
Linear search is a search algorithm, that checks for the key in a set of values one by one till it reaches the end of all the elements.
1.2 Understanding Linear Search with an example
For example:
Consider the array [14, 96, 27, 5, 48], and we need to search for the number 48. Below are the number of iterations necessary:
Consider the array given below and the key is 48.
[14, 96, 27, 5, 48]
if key == a[0]
else if key == a[1]
else if key == a[2]
else if key == a[3]
else if key == a[4]
If the key is found we shall display the index of the key, else we return key not found.
Pseudo Code:
Input:
array
array_len
key
Algorithm:
linearSearch(arr, len, key)
for i = 0 to n-1
if (arr[i] == key)
return i
end if
end for
return -1; // key not found
1.3 Implementation of Linear Search in C
#include<stdio.h>
void linearSearch(int *array, int len, int key)
{
int i = 0;
//Iterate one by one to find the key
for(i = 0; i< len ; i++ )
{
//check one by one if the data at the index is same as key
if(array[i] == key)
{
printf("Key found at index = %d\n", i+1);
return; //return statement is important.
//else it will continue to loop after the element is found
}
}
printf("Not able to find key\n");
}
int main()
{
int arr[5] = {10, 30, 48, 45, 78};
int arrayLen = 5;
int key = 45;
int key_2 = 34;
//successful search
linearSearch(arr,arrayLen, key);
//key not found case
linearSearch(arr,arrayLen, key_2);
return 0;
}
1.4. Output of the program
Key found at index = 4
Not able to find key
1.5. Time complexity of Linear Search
Time complexity is O(n).