WAP to search an element in Array using "Linear Search".
Objective
Write a C++ program to search for an element using Linear Search.
Algorithm / Approach
- Initialize an array with values.
- Read the search target
nfrom the user. - Set a
flag = 0. - Loop through every element of the array from index 0 to the end.
- If
a[i] == n, setflag = 1, print the index, andbreakthe loop. - If the loop finishes and
flag == 0, print "Not found".
main.cpp
#include<iostream>
using namespace std;
int main() {
int a[10]={10,14,19,26,27,31,33,35,42,44};
int i,n,flag=0;
cout<<"Enter no. to Search: ";
cin>>n;
for(i=0; i<=10; i++) {
if(a[i]==n) {
flag=1;
break;
}
}
if(flag==1) {
cout<< n<<" found at "<< i;
}
else {
cout<<"Number not found.";
}
return 0;
}
Expected Output
OUTPUT : 1 Enter no. to Search: 33 33 found at 6 pos OUTPUT : 2 Enter no. to Search: 71 Number not found.
Explanation of the Program
- Linear Search is the simplest searching algorithm. It works exactly like looking for a book on a shelf by checking every single book from left to right.
- It is highly effective for small or unsorted arrays, but scales poorly for massive datasets because it might have to check every single element before finding what it needs.
Complexity
Time Complexity
O(n) - In the worst case, the target is at the very end of the array.
Space Complexity
O(1)