Open In App

C Program for Linear Search

Linear Search is a sequential searching algorithm in C that is used to find an element in a 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.

  1. Check each element in the list by comparing it to the key.
     
  2. If any element is equal to the key, return its index.
     
  3. 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 program to implement linear search using loops
#include <stdio.h>
 
// linear search function that searches the key in arr
int linearSearch(int* arr, int size, int key)
{
    // starting traversal
    for (int i = 0; i < size; i++) {
        // checking condition
        if (arr[i] == key) {
            return i;
        }
    }
    return -1;
}
 
// Driver code
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;
 
    // calling linearSearch
    int index = linearSearch(arr, size, key);
 
    // printing result based on value returned by
    // linearSearch()
    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 Program to implement linear search using recursion
#include <stdio.h>
 
// Function to perform linear search
int linearSearch(int* arr, int size, int key)
{
    // if there are no elements, return -1
    if (size == 0)
        return -1;
 
    // if the element at (size - 1) index is equal to key,
    // return (size - 1)
    if (arr[size - 1] == key) {
        return size - 1;
    }
 
    // if not, call linear seach for same array arr but
    // reducing the size by a single element
    return linearSearch(arr, size - 1, key);
}
 
// Driver code
int main()
{
    int arr[5] = { 6, 7, 9, 1, 5, 11, 8, 12, 2, 3 };
    int size = sizeof(arr) / sizeof(int);
    int key = 4;
 
    // calling linearSearch function
    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!


Article Tags :