Linear Search Algorithm
(Sequential Search)



What is Search?

Searching is a process of finding a value in a list of values. In other words, searching is the process of locating the given value position in a list of values.

Searching is the process of finding the given element in a list of elements

Linear Search Algorithm (Sequential Search Algorithm)

Linear search algorithm finds the given element in a list of elements with O(n) time complexity where n is the total number of elements in the list. This search process starts comparing the search element with the first element in the list. If both are matched then the result is "element found" otherwise the search element is compared with the next element in the list. If both are matched, then the result is "element found". Otherwise, repeat the same with the next element in the list until the search element is compared with the last element in the list. If that last element also doesn't match with the search element, then the result we get is "Element not found in the list". That means, the search element is compared with all the elements in the list sequentially until the match found.

Linear search is implemented using following steps...

  • Step 1: Read the search element from the user
  • Step 2: Compare, the search element with the first element in the list.
  • Step 3: If both are matched, then display "Given element found!!!" and terminate the function
  • Step 4: If both are not matched, then compare search element with the next element in the list.
  • Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in the list.
  • Step 6: If the last element in the list is also not matched, then display "Element not found!!!" and terminate the function.

Example

Consider the following list of element and search element...

Linear Search

Program to implement Linear Search Algorithm using C.

#include<stdio.h>
#include<conio.h>

void main(){
  int list[20],size,i,sElement;

  printf("Enter size of the list: ");
  scanf("%d",&size);

  printf("Enter any %d integer values: ",size);
  for(i = 0; i < size; i++)
    scanf("%d",&list[i]);

  printf("Enter the element to be Search: ");
  scanf("%d",&sElement);
  
  // Linear Search Logic
  for(i = 0; i < size; i++)
  {
     if(sElement == list[i])
     {
        printf("Element is found at %d index", i);
        break;
     }
  }
  if(i == size)
     printf("Given element is not found in the list!!!");
  getch();
}