#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[50],x,n,beg,end,mid,flag;
cout<<"////////////////BINARY SEARCH//////////////////";
cout<<"\n enter the size of array";
cin>>n;
cout<<" enter the sorted array";
for(int i=1;i<=n;i++)
cin>>a[i];
cout<<" enter the element to search";
cin>>x;
beg=1;
end=n;
mid=(beg+end)/2;
while(beg<=end)
{
mid=(beg+end)/2;
if(a[mid]==x)
{
flag=1;break;
}
else if(x<a[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
}
if(flag==1)
cout<<"element found at position "<<mid;
else
cout<<" element is not in above array";
getch();
}
Showing posts with label SEARCHING. Show all posts
Showing posts with label SEARCHING. Show all posts
Monday, February 21, 2011
Sunday, February 20, 2011
LINEAR SEARCH
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[50],n,x,flag;
cout<<"/////////////////// LINEAR SEARCH//////////////////";
cout<<"\n enter the size of array (max 50)";
cin>>n;
cout<<"\n enter array elements";
for(int i=1;i<=n;i++)
cin>>a[i];
cout<<"\n enter an element you want to search";
cin>>x;
for(int j=1;j<=n;j++)
{
if(a[j]==x)
{
flag=1;break;
}
else
flag=0;
}
if(flag==1)
cout<<"\n element found at position "<<j;
else cout<<"element not found";
getch();
}
#include<conio.h>
void main()
{
clrscr();
int a[50],n,x,flag;
cout<<"/////////////////// LINEAR SEARCH//////////////////";
cout<<"\n enter the size of array (max 50)";
cin>>n;
cout<<"\n enter array elements";
for(int i=1;i<=n;i++)
cin>>a[i];
cout<<"\n enter an element you want to search";
cin>>x;
for(int j=1;j<=n;j++)
{
if(a[j]==x)
{
flag=1;break;
}
else
flag=0;
}
if(flag==1)
cout<<"\n element found at position "<<j;
else cout<<"element not found";
getch();
}
Subscribe to:
Posts (Atom)