Linear Search in C++

Linear Search in C++

        Linear search is the simplest and traditional searching approach. There is no need to sort the array you can directly search the required value. 

        The approach is using a loop to access each element of the array and check if that element matches with the user-provided value. If the match is found break the loop and print element is found else print element is not found.

        O(n) is the time complexity of linear search, where n is number of elements in an array.



Code

#include <bits/stdc++.h>
using namespace std;

int main() {
    
    int a[5]={1,9,45,78,2};                         // the array with size 5
    
    cout<<"Enter the element to search: ";          // requesting element to search
    int n;
    cin>>n;
    
    int flag=0;                                 // to check element is found or not by default keeping it as not found
    
    for(int i=0;i<5;i++){                       // loop to access each element 
        if(a[i]==n){                            // match found update flag to 1 and break the loop
            flag=1;
            break;
        }
    }
    
    if(flag==0){                                    // flag is zero element not found
        cout<<"Element not found!";
    }
    else{                                           // flag is one element found
        cout<<"Element found!";
    }
    
    return 0;
}


Output

Enter the element to search: 2
Element found!


Program may also be asked as:

  1. Explain linear search in c++ using function
  2. Explain linear search in c++ using recursion
  3. Execute a linear search example
  4. Explain linear search in c++ with algorithm
  5. Explain linear search in c using array
  6. Write an algorithm for linear search in c++ cpp
  7. Execute code for linear search in c++ cpp
  8. Implement linear search in c++ cpp
  9. Recursive linear search in c++ cpp
  10. Execute Linear search program in c++ with time complexity
  11. Write a program to implement linear search in c++ cpp

Post a Comment

0 Comments