Searching

Sequential searching

Sequential searching is a searching technique to find an item from a list until the particular item not found or list not reached at end.

Code in C++

#include<iostream.h>
#include<conio.h>
int main()
{

int a[5]={1,2,3,4,5};
int i,loc=-1;
int n;
cout<<“Enter a no:”;
cin>>n;
for(i=0;i<5;i++)

if(a[i]==n)
loc=i;
if(loc==-1)
cout<<“Value not found…”;
else
cout<<“Value in index:”<<loc;

getch();
}

Binary Search

It works on sorted list. This method starts by comparing the searched element to the elements in the middle of the list. If the comparison determines that the two elements are equal the method stops and returns the position of the element. If the searched element is greater than the middle element, it starts the method again using only the bottom half of the sorted list. If the searched element is less than the middle element, it starts the method again using only the top half of the sorted list.

Code in C++

#include<iostream.h>
#include<conio.h>
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
int i,s,e,m,loc=-1;
int n;
s=0,e=9,m=0;
cout<<“Enter a value which u wanted to be found:”;
cin>>n;
while (s<=e)
{
m=(s+e)/2;
if(a[m]==n)
{
loc=m;
break;
}
else if(n<a[m])
e=m-1;
else
s=m+1;
}
if(loc==-1)
cout<<n<<“is not found”<<endl;
else
cout<<n<<” is found at index ‘”<<loc<<“‘”<<endl;
getch();
}

Print Friendly

Share this with your friends

One Comment to “Searching”

  1. A piece of ertoiuidn unlike any other!

Leave a Reply

Your email address will not be published. Required fields are marked *