Implement Linear Search in C

In this blog post, you will learn what is linear search and how to implement linear search in C with the help of programming examples.

So let’s first understand the linear search.

 

What is Linear Search?

Some people also call it sequential search. It is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.

Basic algorithm:

Suppose Arr is a given integer array of n elements. These elements are Arr, Arr, Arr, … Arrn-1 . And the target value T, the following steps are used to find the index of the target T in Arrn .

  1. Set i to 0.
  2. If Arri= T, the search terminates successfully; return “i”.
  3. Increase “i” by 1.
  4. If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.

 

Now for a better understanding let’s see a problem statement. It also gives you the idea that how people ask questions in the interview related to linear search.

Problem Statement: Given an array of size n, and an element T, the task is to find T in the given array. If T is present print the index of the T or print -1.

Example 1:

Input: arr[]= 11 22 13 14 15, num = 14
Output: 3
Explanation: 14 is present in the 3rd index


Example 2:

Input: arr[]= 1 14 31 12 10, num = 17
Output: -1
Explanation: 17 is not present in the given array

 

Now let’s see the solution but it is my recommendation that first try yourself before jumping directly on the solution.

 

Solution: Linear search in C:-

 

// Linear Search in C

#include <stdio.h>

int linearSearch(const int arr[], const int n, const int T)
{
    int i =0;
    int elementIndex = -1;

    // Search sequencially in arr
    for (i = 0; i < n; i++)
    {
        if (arr[i] == T)
        {
            elementIndex = i;
            break;
        }
    }
    return elementIndex;
}

int main()
{
    const int arr[] = {1, 23, 9, 31, 14};
    const int T = 9;

    const int n = sizeof(arr) / sizeof(arr[0]);

    const int ret = linearSearch(arr, n, T);

    printf((ret != -1)? "Element Found":"Element not found");

    return 0;
}

Output:

Element Found

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *