C Program for Linear Search
Last Updated :
26 Sep, 2023
Linear Search is a sequential searching algorithm in C that is used to find an element in a list.
- We can implement linear search in C to check if the given element is present in both random access and sequential access data structures such as arrays, linked lists, trees, etc.
- Linear Search compares each element of the list with the key till the element is found or we reach the end of the list.
In this article, we will see the iterative and recursive linear search programs in C programming language.
Algorithm for Linear Search in C
Let key be the element we are searching for.
- Check each element in the list by comparing it to the key.
- If any element is equal to the key, return its index.
- If we reach the end of the list without finding the element equal to the key, return some value to represent that the element is not found.
Linear Seach Program in C (Iterative)
C
#include <stdio.h>
int linearSearch( int * arr, int size, int key)
{
for ( int i = 0; i < size; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main()
{
int arr[10] = { 3, 4, 1, 7, 5, 8, 11, 42, 3, 13 };
int size = sizeof (arr) / sizeof (arr[0]);
int key = 4;
int index = linearSearch(arr, size, key);
if (index == -1) {
printf ( "The element is not present in the arr." );
}
else {
printf ( "The element is present at arr[%d]." , index);
}
return 0;
}
|
Output
The element is present at arr[1].
Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(1)
Linear Search Program in C (Recursive)
C
#include <stdio.h>
int linearSearch( int * arr, int size, int key)
{
if (size == 0)
return -1;
if (arr[size - 1] == key) {
return size - 1;
}
return linearSearch(arr, size - 1, key);
}
int main()
{
int arr[5] = { 6, 7, 9, 1, 5, 11, 8, 12, 2, 3 };
int size = sizeof (arr) / sizeof ( int );
int key = 4;
int index = linearSearch(arr, size, key);
if (index == -1) {
printf ( "The element is not present in the list." );
}
else {
printf ( "The element is present at arr[%d]." , index);
}
return 0;
}
|
Output
The element is not present in the list.
Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(n)
Note: If the compiler performs tail call optimization, then Auxiliary Space for recursive approach can be reduced to O(1).
Please refer complete article on Linear Search for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...