Sunday, 5 June 2011

Ternary search programm in c++

#include<iostream.h>
void main()
{
int i,j,n,l,u,loc,a[1000],x,y,p;
cout<<"No of Element : "; cin>>n;
cout<<"\n";
cout<<"Array  :"<<endl;
for(p=1;p<=n;p++)
{
cout<<"array ["<<p<<"] = "; cin>>a[p];
}
cout<<"Location search item : ";
  cin>>y;
 i=1;
 j=n;
 while(i<j-1)
 {
 l = (i+j)/3;
 u = (2*(i+j))/3;
 if(y>a[u])
 {
 i= u+1;
 }
 else if(y>a[l])
 {
 i=l+1;
 j=u ;
 }
 else
 {j=l;}
    }

 if(y == a[i])
 {loc = i;
 cout<<"Location :"<<loc<<" position";
 }
 else if(y == a[j])
 {loc = j;
 cout<<"Location :"<<loc<<" position";
 }
 else
 {loc=0;
 cout<<"Location :"<<loc<<" position";
 }
}
Editing & program by "Shojib"

No comments:

Post a Comment