Friday 14 September 2012

To perform the linear search operation

Description: The linear search is most simple serching method. It does not expect the list to be sorted. The key which is to be searched is compared  with each element of the list one by one. If a match exists, the search is terminated. If the end of list is reached it means that the search has failed and key has no matching in the list.
ALGORITHM:

      LINEAR SEARCH

1. Start

2. Read the value of n

3. for i=1 to n increment in steps of 1
            Read the value of ith element into array

4. Read the element(x) to be searched

5. search<--linear(a,n,x)

6. if search equal to 0 goto step 7 otherwise goto step 8

7. print unsuccessful search

8. print successful search

9. stop

       LINEAR FUNCTION

1. start
2. for i=1 to n increment in steps of 1
3. if m equal to k[i] goto step 4 otherwise goto step 2
4. return i
5. return 0
6. stop


        Program:
#include<stdio.h>
main()
{
int i,j,n,a[10],key;
clrscr();
printf("enter range for array:");
scanf("%d",&n);
printf("enter elements into array:");
for(i=0;i<=n;i++)
scanf("%d",&a[i]);
printf("enter the search element:");
scanf("%d",&key);
for(i=0;i<=n;i++)
{
if(key==a[i])
{
printf("element %d found at %d",key,i);
break;
}
else
if(i==n)
printf("element %d not found in array",key);
}
getch();
}
        Input/Output:
enter range for array:4
enter elements into array:56
43
12
88
9
enter the search element:9
element 9 found at 4

enter range for array:5
enter elements into array:23
12
56
34
3
8
enter the search element:3
element 3 found at 4
conclusion: the program is error free
VIVA QUESATIONS:

1)  Define linear search ?
Ans : The linear search is most simple serching method. It does not expect the list to be sorted. The key which is to be searched is compared  with each element of the list one by one. If a match exists, the search is terminated. If the end of list is reached it means that the search has failed and key has no matching in the list.

No comments:

Post a Comment