Linear Search :

Linear search is a very basic and simple search algorithm.
In Linear search, we search an element or value in a given array by traversing the array from the starting, till the desired element or value is found.
For example, consider an array of integers of size N You should find and print the position of all the elements with value. Here, the linear search is based on the idea of matching each element from the beginning of the list to the end of the list with the integer and then printing the position of the element if the condition is `True'.


Linear Search Visualization

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] A[10]
0 1 2 3 4 5 6 7 8 9 10


 

      


Trace
  • procedure linear_search (list, value)
  •  while i < n
  •      if match item == value
  •       return the item's location
  •      i++
  • end while
  • end procedure




Linear Search Code in C:

                      
                        #include <stdio.h>
 
                          int main()
                          {
                            int array[100], search, c, n;
                           
                            printf("Enter number of elements in array\n");
                            scanf("%d", &n);
                           
                            printf("Enter %d integer(s)\n", n);
                           
                            for (c = 0; c < n; c++)
                              scanf("%d", &array[c]);
                           
                            printf("Enter a number to search\n");
                            scanf("%d", &search);
                           
                            for (c = 0; c < n; c++)
                            {
                              if (array[c] == search)    /* If required element is found */
                              {
                                printf("%d is present at location %d.\n", search, c+1);
                                break;
                              }
                            }
                            if (c == n)
                              printf("%d isn't present in the array.\n", search);
                           
                            return 0;
                          }