The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
Linear search, also called as orderly search or sequential search, because every key element is searched from first element in an array ie) a[0] to last element in an array ie) a[n-1]. Linear search algorithm works by comparing every element in an array with the key element. If a key element matches any element in the array, it stop search and return the location of key element in the array.
Here is the program to demonstrate Linear Search.
#include <stdio.h>
int main()
{
int arry[10],key, i, n, found=0,pos =-1;
printf("\n Enter the size of the array : ");
scanf("%d", &n);
printf("\n Enter %d elements in the array : \n",n);
for(i=0; i<n; i++)
{
scanf("%d", &arry[i]);
}
printf("\n Enter the key element that has to be search : ");
scanf("%d", &key);
for(i=0;i<n;i++)
{
if(arry[i] == key)
{
found = 1;
pos = i;
printf("\n %d is found in the array at position arry [%d]", key, i);
break;
}
}
if(found == 0)
printf("\n %d does not exist in the array", key);
return 0;
}
Enter the size of the array : 5 Enter 5 elements in the array : 1 2 3 4 5 Enter the key element that has to be search : 3 3 is found in the array at position arry [2]
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019