Searching and sorting- Linear Search


bool search(int arr[],int size,int key)

{
for(int i=0;i<n;i++)
{
      if(arr[i]==key)
       {
          return 1;
       }
}
return 0;
}

Time complexity = O(n)
space complexity=O(1)


Approach:

In Linear search, we have given an array, the size of the array, and the key element that we have to find in the array whether the key element is present in the array or not. If the key element is present in an array then return true otherwise return false.


Step-1:-Now, make a function for searching the key element and pass the array, size of the array, and key element you want to find. Also return type of function is bool because we just want that key element to be present or not. So, basically, we want if present then True otherwise False and for this, we have to use Bool return type.

      bool search(int arr[],int size,int key)

{

    //code

}

Step-2: For finding key elements in an array we have to traverse the array from start to its size i.e from 0-->size. So we have to take an int variable as i=0 (array starts from 0 or you can also use 1 instead of 0 but keep in mind for i=1 we have to take size also i.e i <=size)

  bool search(int arr[],int size,int key)

  {       

            for(int i=0;i<size;i++)

  }

Step-3: Now inside for loop compare the key element with the array element. If matched then return true otherwise return false.

bool search(int arr[],int size,int key)

      {  

      for(int i=0;i<size;i++)

           {

                  if(arr[i]==key)

                        {

                             return 1;

                         }

           }

return 0;

}








Comments

Popular posts from this blog

How to connect Epson L3150 printer to wifi?

IKAGAI- The Japanese secret to long and happy life

BULLYING:-The facts we are not aware of