Tuesday, 21 February 2017

Implementation of Linear Search Algorithm in C++

In computer science, linear search or sequential search is a method for finding a target value within a list or Array. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.

Worst Case Time Complexity is: O(n)


Algorithm:
1. set: item=elemet to be found in the array
2. set: flag=0
3. For i in range 1 to n
4.         if array[i]=item
5.                  set: flag=1
6.                  set: loc=i
7.                  break
8.         EndIf
9. EndFor
10.If flag=1
11.     print loc
12.Else
13.     print "Element is not found"
14.Exit


Program:-
#include <stdio.h>
#define MAX 100

class linearsearch{
 
    private:
          int array[MAX],n;
    public:
          void get_data();
          int search_element();
          void print();
};
void linearsearch::get_data()
{
   printf("\nEnter the total number of elements: ");
   scanf("%d",&n);
   printf("\nEnter the elements of array: \n");
      for(int i=0;i<n;i++)
      {
             scanf("%d",&array[i]);
      }
}
int linearsearch::search_element()
{
   int loc,item,flag=0;
   printf("\nEnter the element to be searched: ");
   scanf("%d",&item);
   for(int i=0;i<n;i++)
   {
          if(item==array[i])
          {
                   flag=1;
                   loc=i+1;
                   break;
          }
   }
   if(flag==1)
   {
        return loc;
   }
   else
   {
        return flag;
   }
}
void linearsearch::print()
{
   printf("\nThe elements of array are: \n\n");
   for(int i=0;i<n;i++)
   {
         printf("%d ",array[i]);
   }
}
int main()
{
   linearsearch ls;
   ls.get_data();
   ls.print();
   int loc=ls.search_element();
   if(loc==0)
   {
           printf("\nElement is not present in the array");
   }
   else
   {
           printf("\nElement is found at %d",loc);
   }
   return 0;
}


Output:-

 


EmoticonEmoticon