Searching Algorithms - Linear Search

Linear Search

Linear search is a basic and very simple search algorithm. This type of search searches an element or value from an array until the desired element or value is found and it searches in sequential order. It compares the element with all other elements in the given list or array and if the element is matched it returns the index of the matched element else it returns -1. Linear Search is applied on the unsorted or unordered list when there are fewer elements in a list.
Algorithm:
linear_search(int a[ ], int n, int x)

Step 1: Set i = 0.
Step 2: If i > n then goto Step 7.
Step 3: If a[i] == x, goto Step 6.
Step 4: Increment i by 1.
Step 5: Goto Step 2.
Step 6: Print element found at the index i and goto Step 8.
Step 7: Print Element not found.
Step 8: End.
C Program:
Here is source code of the C Program to implement Linear Search. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

#include<stdio.h>

int linear_search(int elems[], int n, int x);

void main()
{
    int elems[20], n, x, i, pos;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter the elements of array: ");
    for (i=0; i<n; i++)
    {
        scanf("%d", &elems[i]);
    }

    printf("Enter the number to search: ");
    scanf("%d", &x);

    pos = linear_search(elems, n, x);

    if (pos == -1)
    {
        printf("\n%d is not present in the array.\n", x);
    }
    else
    {
        printf("\n%d is present at the location %d.\n", x, pos+1);
    }
}

int linear_search(int elems[], int n, int x)
{
    int i;
    for (i=0; i<n; i++)
    {
        if (elems[i] == x)
        {
            return i;
        }
    }
    return -1;
}
Output:

Enter the number of elements: 10
Enter the elements of array: 10
14
19
26
27
31
33
35
42
44
Enter the number to search: 33

33 is present at the location 7.
Share on Google Plus

About AlgoStream

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment