Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

LAB 4

~S SOUMYA
QUESTION-01:-Implement the linear search algorithm using C language.
CODE:-
#include<stdio.h>
main()
{
int i,size,n=0,x;
printf("enter the size of the array:");
scanf("%d",&size);
int arr[size];
for(i=0;i<size;i++)
{
printf("arr[%d] ",i);
scanf("%d",&arr[i]);
}
printf("\nThe elements in the array are:");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
printf("\n\nenter the element to be searched:");
scanf("%d",&x);
for(i=0;i<size;i++)
{
if(arr[i]==x)
{
n=n+1;
}
}
if(n==0)
{
printf("Searched element not found\n");
}
else
{
printf("Searched element is found %d times in the array",n);
}
}
Output:-
QUESTION 2:-Implement the Binary search algorithm using C language.
Code:-
#include<stdio.h>
main()
{
int i,size,n=0,x;
printf("enter the size of the array:");
scanf("%d",&size);
int arr[size];
for(i=0;i<size;i++)
{
printf("arr[%d] ",i);
scanf("%d",&arr[i]);
}
printf("\nThe elements in the array are:");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
int j,temp;
for(i=0;i<size;i++)
{
for(j=i;j<size;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
n=0;
printf("\nenter the element to be searched:");
scanf("%d",&x);
int l=0,r=size-1,mid;
while(l<=r)
{
mid=(l+r)/2;
if(arr[mid]==x)
{
n=n+1;
for(i=mid-1;i>=0;i--)
{
if(arr[i]==x)
{
n=n+1;
}
else
{
break;
}
}
for(i=mid+1;i<size;i++)
{
if(arr[i]==x)
{
n=n+1;
}
else
{
break;
}
}
break;
}
else if(arr[mid]>x)
{
r=mid-1;
}
else
{
l=mid+1;
}
}
if(n==0)
{
printf("Searched element not found\n");
}
else
{
printf("Searched element is found %d times",n);
}
}
Output:-

You might also like