TEAM CODING-BCA

LINEAR , BINARY AND INTERPOLATION SEARCH

SEARCHING


#include<stdio.h>
#include<stdlib.h>
#define n 10
void linear();
void binary();
void interpolation();
int arr[n];
void main()
{
int i,ch,j;
printf("enter the array:-");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
while(1)
{
printf("enter 1 for linear 2 for binary 3 for interpolation 4 to exit ");
scanf("%d",&ch);
switch(ch)
{
case 1:
linear(arr);
break;
case 2:
binary(arr);
break;
case 3:
interpolation(arr);
break;
case 4:
exit(0);
}
}
}



void linear(int arr[])
{
int i,s,f=0;
printf("\n enter the number you want to search:-");
scanf("%d",&s);
for(i=1;i<=n;i++)
{
if(arr[i]==s)
{
f=1;
break;
}
}
if(f==0)
printf("value not found");
else
printf("value found at position %d ",i+1);

}


void binary(int arr[])
{
int mid,low,high,s,i,f=0;
low=0;
high=n-1;
printf("\n enter the number you want to search:-");
scanf("%d",&s);
while(low<high)
{
mid=(low+high)/2;
if(s<arr[mid])
{
high=mid-1;
}
if(s>arr[mid])
{
low=mid+1;
}
if(s==arr[mid])
{
f=1;
break;
}
}
if(f==0)
printf("value not found");
else
printf("value found at position %d ",mid+1);
}


void interpolation(int arr[n])
{
int mid,low,high;
int s,i,f=0;
low=0;
high=n-1;
printf("\n enter the number you want to search:-");
scanf("%d",&s);

while(low<high)
{
mid=low+(high-low)*( (s-arr[low])/(arr[high]-arr[low]));
if(s<arr[mid])
{
high=mid-1;
}
if(s>arr[mid])
{
low=mid+1;
}
if(s==arr[mid])
{
f=1;
break;
}
}
if(f==0)
printf("value not found");
else
printf("value found at position %d ",mid+1);
}

SEARCHING

No comments:

Post a Comment