DATA STRUCTURES



Admission Enquiry Form

Linear Search in an Array.

Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the elements in the array.



Algorithm of Linear Search in an Array

Linear Search(A,N,ITEM)

Step1. START

Step2. LOC  <-   -1 [Initialize Location Counter]

Step3. I <- 1 [Initialize Counter]

Step4. [Search for ITEM]

             Repeat while I    N and A[I]      ITEM

                        I <- I + 1  

             [End of loop]

Step5.  If A[I] <- ITEM then [Successful]

                    LOC <- I

              [End of If Structure]

Step6.   END


Program of Linear Search in an Array.

#include<stdio.h>
#include<conio.h>
void linear_search(int arr[],int n,int element)
{
int i,flag=0;
for(i=0;i<n;i++)
{
if(arr[i]==element)
{
flag=1;
printf("Element found at location %d",i+1);
break;
}
}

if(flag==0)
{
printf("Element not found");
}
}//end of function linear_search

int main()
{
int a[20],i,element,n;
printf("How many elements you want to enter <= 20 ?\n");
scanf("%d",&n);

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

printf("\nEnter element to search:");
scanf("%d",&element);

linear_search(a,n,element);

getch();
}//end of main function.