Linear Search | Data Structures and Algorithms

Linear Search | Data Structures and Algorithms

Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. It is the easiest search algorithm

Time complexity: O(N)

Auxiliary Space: O(1)

Follow the given steps to solve the problem:

  • Start from the leftmost element of array[] and one by one compare target(variable) with each element of array[]

  • If target(variable) matches with an element, return the index.

  • If target(variable) doesn’t match with any of the elements, return -1.

Code:


#include <iostream>
using namespace std;

int LinearSearch(int array[],int target,int size)
{
    for(int i=0;i<size;i++)
    {
        if(array[i] == target)
        {
            return i;
        }
    }
     return -1;
}

int main() {

    int array[]={2,3,6,10,14};

    int target= 10;

    int size = sizeof(array)/sizeof(array[0]);

    int result = LinearSearch(array,target,size);

    if(result==-1)
    {
        cout<<"Not Found";
    }
    else{
        cout<<"Found at index: "<<result;
    }
    return 0;
}

Output:

Found at index: 3