program for linear search
#include<iostream.h>
#include<conio.h>
int a[15],i,n,item;
void read();
int lsearch(int [],int,int);
void main()
{
int p;
clrscr();
read();
cout<<"Enter the search element\n";
cin>>item;
p=lsearch(a,n,item);
cout<<"\nElement found at "<<p+1<<" position";
getch();
}
int lsearch(int a[],int n,int item)
{
for(i=0;i<n;i++)
{
if(a[i]==item)
{
break;
}
}
return(i);
}
void read()
{
cout<<"Enter the limit\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
}
In Linear Search the list is searched sequentially and the position is returned if the key element to be searched is available in the list, otherwise -1 is returned.. The search in Linear Search starts at the beginning of an array and move to the end, testing for a match at each item. All the elements preceding the search element are traversed before the search element is traversed. i.e. if the element to be searched is in position 10, all elements form 1-9 are checked before 10.
#include<iostream.h>
#include<conio.h>
int a[15],i,n,item;
void read();
int lsearch(int [],int,int);
void main()
{
int p;
clrscr();
read();
cout<<"Enter the search element\n";
cin>>item;
p=lsearch(a,n,item);
cout<<"\nElement found at "<<p+1<<" position";
getch();
}
int lsearch(int a[],int n,int item)
{
for(i=0;i<n;i++)
{
if(a[i]==item)
{
break;
}
}
return(i);
}
void read()
{
cout<<"Enter the limit\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
}
In Linear Search the list is searched sequentially and the position is returned if the key element to be searched is available in the list, otherwise -1 is returned.. The search in Linear Search starts at the beginning of an array and move to the end, testing for a match at each item. All the elements preceding the search element are traversed before the search element is traversed. i.e. if the element to be searched is in position 10, all elements form 1-9 are checked before 10.
No comments:
Post a Comment