Implement Linear Search using C++

Technology and generation are growing up together, and the younger generation users are somewhat connected with tech and the internet all the time. Not to mention, today the whole world in this time of crisis is working over the internet. But to make these technologies, softwares, etc a software developer must have excellent problem-solving skills. In this world where the internet is the new fuel, one needs to be pretty sharp. And by sharp, for software developers, it means knowing how to automate real-world problems using computer programs. Data structures help a lot in this journey of logic building. So today we’re going to write a simple data structure program to Implement Linear Search using C++.

 

What is A Linear Search?

 

Linear search is the most basic searching for all algorithms in data structures. Also, it’s pretty easy to understand. But due to its slow searching speed, the Linear search algorithm is pretty rare to see in practical usage.

 

In a list/array to use Linear search one has to traverse the list/array at a time. Due to this reason, the time complexity of this algorithm is higher.

 

What’s The Approach?

 

  • In an input array, we’ll start with the leftmost element index. We’ll traverse the array one by one comparing the number to be found (x) with the element present in the array. 

 

  • If X matches with the array element then we’ll print the index. Otherwise, we’ll return -1.

 

Also Read: Multiply Integers without Multiplication Arithmetic Operator in C++

 

C++ Program To Implement Linear Search

 

Input:

2, 3, 4, 10, 40 

 

Output:

Element is present at index 3

 

// C++ code to Linear Search

#include <iostream>
using namespace std;

int search(int arr[], int n, int x)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == x)
            return i;
    return -1;
}

// Driver code
int main(void)
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int n = sizeof(arr) / sizeof(arr[0]);

    // Function call
    int result = search(arr, n, x);
    (result == -1)
        ? cout << "Element is not present in array"
        : cout << "Element is present at index " << result;
    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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