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:
- Explain linear search in c++ using function
- Explain linear search in c++ using recursion
- Execute a linear search example
- Explain linear search in c++ with algorithm
- Explain linear search in c using array
- Write an algorithm for linear search in c++ cpp
- Execute code for linear search in c++ cpp
- Implement linear search in c++ cpp
- Recursive linear search in c++ cpp
- Execute Linear search program in c++ with time complexity
- Write a program to implement linear search in c++ cpp
0 Comments