Friday, June 18, 2021
Home coding Write a program to search an element using linear search.

Write a program to search an element using linear search.

Given a number,we have to search an element using linear search in an array.

So what is Linear Search?

we perform linear search to find an element in an array.it search element sequentially one by one.

Example:

input:arr[]={1,2 ,3,4,5,6}   k=4
output: true 

Logic:

step 1:it will start searching element from 0th index to nth index
step 2-compare each element with the value u looking for.
step 3-if element found return true. 

Code-

#include<bits/stdc++.h>
using namespace std;
int main()
{
   int arr[]={1,2,3,5,6};
   int k=3;
   int flag=0;
   int n=sizeof(arr)/sizeof(arr[0]);
   for(int i=0;i<n;i++)
   {
       if(k==arr[i])
       {
           cout<<"element found"<<endl;
           flag=1;
           break;
       }
   }
   if(flag==0)
   {
       cout<<"element not present"<<endl;
   }
}

Output:

element found

Time complexity:0(N) worst case happen when element is not present.

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments