Sunday, July 4, 2010

PROGRAM TO ILLUSTRATE LINEAR,BINARY AND INTERPOLATION SEARCHES(DS)

Buzz It

#include<iostream.h>
#include<conio.h>
class search
{
int a[100],size,i,j,temp;
public:
void linear(int);
void binary(int);
void interpolation(int);
void getarray();
void display();
void sort();
search()
{
size=0;
} };
void search::get array ()
{
cout<<"enter max size\n";
cin>>size;
cout<<"enter array elements\n";
for (i=0; i<size++)
{
cin>>a[i];
}}
void search::display ()
{
cout<<"the array is\n";
for (i=0; i<size-1; i++)
{
cout<<a[i];
}
}
void search::linear (int x)
{
int i;
for (i=0; i<size; i++)
}
if (a[i]==x)
{
cout<<"found key at the position\n"<<i;
return;
}
}
cout<<"not found\n";
}
void search::binary (int x)
{
int big=0;
int mid, end;
end=size-1;
while (big<=end)
{
mid= (big+end)/2;
if (a[mid]==x)
{
cout<<"found at\n"<<mid;
return;
}
else if (a[mid]<x)
{
big=mid+1;
}
else
end =mid-1;
}
cout<<"not found\n";
}
void search::sort ()
{
for(i=0;i<size-1;i++)
{
for(j=0;j<size-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"sorted list is \n";
for (i=0;i<size;i++)
cout<<a[i]<<"\n";
}
void search::interpolation (int x)
{
int mid;
int big=0;
int end=size-1;
while (big<=end)
{
mid=big+ ((x-a[big])*(end-big))/(a[mid]-a[big]);
if (a[mid]==x)
{
cout<<"element found at the position\n"<<mid<<"\n";
return;
}
else if (a[mid]<x)
{
big=mid+1;
}
else
end=mid-1;
}
cout<<"not found\n";
}
void main ()
{
int c,x;
clrscr ();
search ob;
do
{
cout<<"menu\n1-get array\n2-display\n3-binary\n4-linear\n5-
interpolation\n";
cin>>c;
switch(c)
{
case 1:ob.getarray();
break;
case 2:ob.display();
break;
case 3:cout<<"enter the element to search\n";
cin>>x;
ob.sort ();
ob.binary(x);
break;
case 4:cout<<"enter element to search\n";
cin>>x;
ob.linear(x);
break;
case 5:cout<<"enter the element to found\n";
cin>>x;
ob.sort();
ob.interpolation(x);
}}
while(c<=5);
getch ();
}


OUTPUT:
menu
1-get array
2-display
3-binary
4-linear
5-interpolation
1e
Enter max size
2e
Enter array elements
56
menu
1-get array
2-display
3-binary
4-linear
5-interpolation
2
the array is
56
menu
1-get array
2-display
3-binary
4-linear
5-interpolation
3e
Enter the element to search
5s
Sorted list is
56found at0

0 comments:

Post a Comment