Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Linear Search Alogrithm

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 322
    Comment on it

    You all will agree to this that linear search is the most simple search algorithm we have read among all other algorithms. Right!?! In this type of search , every item in a list is checked one by one, i.e, a sequential search is made over all items in a list. And if a match is found, that is, the item we a looking for is found then that particular item is returned otherwise the search continues till the end of the list.

     

    Algorithm:

    Linear Search(Array arr, Value item)
    Step 1: Set i to 1
    Step 2: if i > n then go to step 7
    Step 3: if arr[i] = item then go to step 6
    Step 4: Set i to i + 1
    Step 5: Go to step 2
    Step 6: Print element item found at index i and go to step 8
    Step 7: Print "element not found"
    Step 8: Exit

     

    In a list with n items, the best case will be the search to be found at first element of the list as that will be the only comparison needed. The worst case will be the case when the value is not in the list or it occurs once at the last of the list, as in this case n comparisons will be needed.

     

    /* Program to search an element in an array of integers using linear search technique */
    
    #include <stdio.h>
    #define MAX 100
    void main (void)
    {
     int a[MAX], i=0, n ,item;
     printf(\n Enter the size of array:);
     scanf(%d, &amp;n);
     if(n &gt; MAX)
     {
      printf(\n Array size input is greater than the declared size\n);
      exit(1);
     }
     printf(Enter the %d elements of an array:,n);
     scanf(%d,&amp;a[i]);
     printf(Enter the element to be searched:);
     scanf(%d,&amp;item);
     while((i &lt; n) &amp;&amp; a[i] != item)
     i++;
     if(i &gt; n)
     {
    printf(\n Element %d you are looking for is not in the list.,item);
     }<br>
     else
      printf(\n %d found at index %d of an array,item,n);
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: