Monday, 10 March 2014

LINEAR SEARCH

DESCRIPTION:-

Linear search is a method for finding a particular value in a list, that consists of checking every one of its  elements, one at a time and in a sequence, until the desired one is found. It is special case of brute-force search. Its worst case cost is proportional to the number of elements in the list.

OPERATION:-

Linear_Search (int str[], int element)
This function takes array and element to be searched as its parameters. This function sequentially search for the element.
 

ALGORITHM:-

Linear_Search (int str[], int element)
1) i <--- 0
2) flag<---0
3) n<---number of entries in array
4) repeat till i<n
5) if str[i] = element
6) then print element found at position i+1 and set flag<---1
7) //end if
8) //end loop
9) if flag = 0
10) then print element not found
11) end
 

PROGRAM CODE:-

#include<stdio.h>
#include<conio.h>
void Linear_Search (int str[5], int element)
{
int flag=0;
int pos=0;
int i;
for(i=0;i<5;i++)
{
if(element==str[i])
{
flag=1;
pos=i+1;
printf("\n Given element is found at position : %d", pos);
}
}
if(flag==0)
{
printf("Given element is not found!!");
}
void main()
{
int str[5],i;
int element=0;
clrscr();
printf("Enter 5 elements :");
for(i=0;i<5;i++)
scanf("%d", &str[i]);
printf("\n Enter element to be searched : ");
Linear_Search (int str[], int element);
getch();
}
 

 OUTPUT:-

Enter 5 elements :
1
2
3
4
5
 Enter element to be searched: 4
 Given element is found at position : 4
 
 
 
 

No comments:

Post a Comment