Linear Search

Afreen

Linear Search Algorithm

Linear Search is a simple sequential search algorithm. In Linear Search, we will traverse the array or list sequentially until the element is found. The main disadvantage of linear search is time complexity. As we deal with unorder data an element can be present at the end of the list, so the worst case could be traversing the array or list till the end.

The time complexity of a linear search is O(n).

Linear Search in C

#include <stdio.h>
long linear_search(long [], long, long);
int main()
{
   int array[5]={4,66,72,5,8}, search, i, n, location;
   printf("Enter search element\n");
   scanf("%d", &search);
   location = linear_search(a, n, search);
   if (location == -1)
      printf("%d isn't present in the array.\n", search);
   else
      printf("%d is present at location %d.\n", search, position+1);
   return 0;
}
int linear_search(int a[], int n, int find) 
{
   int i;
   for (i = 0 ;i < n ; i++ ) {
      if (a[i] == find)
         return i;
   }
   return -1;
}

Output

Enter search element
72
72 is present at location 3.

Explanation:

In the above Linear search program, we traverse the array using for loop and it compares each element with the element to be found. If the element is found it will return the index else it will return -1.

At each iteration, we will compare each element with the search element.

  • If Element matches, then it will return its corresponding index.
  • If not it will move to the next index.
  • If an element does not match with any element from the given array then it will return -1.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.