Linear Search&Binary Search
Linear Search&Binary Search
#include<stdio.h>
void linear(int a[],int n,int key);
void binary(int a[],int n,int key);
void main()
{
int a[50],i,n,ch,key;
printf("\nEnter the size of the array:");
scanf("%d",&n);
printf("\nEnter the array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the element to be searched:");
scanf("%d",&key);
do
{
printf("\nEnter the choice:");
printf("\n1.LINEAR SEARCH\n2.BINARY SEARCH\n3.EXIT");
scanf("%d",&ch);
switch(ch)
{
case 1:linear(a,n,key);
break;
case 2:binary(a,n,key);
break;
case 3:printf("\nExiting....");
break;
default:printf("\nWRONG CHOICE");
}
}while(ch!=3);
}
void linear(int a[],int n,int key)
{
printf("\nPerforming Linear search");
int i,flag=0;
for(i=0;i<n;i++)
{
if(a[i]==key)
{
flag=1;
break;
}
}
if(flag==1)
{
printf("\nElement found at %d",i+1);
}
else
{
printf("\nElement not found");
}
}
void binary(int a[],int n,int key)
{
printf("Peforming bubble sort");
int i,j,temp=0,beg,end,mid;
for(i=0;i<(n-1);i++)
{
for(j=0;j<(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nsorted array is..");
for(i=0;i<n;i++)
{
printf("\n%d\t",a[i]);
}
beg=0;
end=n-1;
mid=(beg+end)/2;
printf("\nEnter the element to be searched:");
scanf("%d",&key);
while(beg<end)
{
if(a[mid]==key)
{
printf("\nElement found at %d",mid+1);
break;
}
else if(key>a[mid])
{
beg=mid+1;
}
else
{
end=mid-1;
}
mid=(beg+end)/2;
}
if(beg>end)
{
printf("\nElement not found:");
}
}
OUTPUT
ubuntu@ubuntu-H81M-S:~/AshwinHarikumar-10$ ./a.out
Enter the size of the array:4
Enter the array elements:
32
15
59
75
Enter the element to be searched:32
Enter the choice:
1.LINEAR SEARCH
2.BINARY SEARCH
3.EXIT
1
Performing Linear search
Element found at 1
Enter the choice:
1.LINEAR SEARCH
2.BINARY SEARCH
3.EXIT
2
Performing bubble sort
sorted array is.
32
15
59
75
Enter the element to be searched:59
Element found at 3
Enter the choice:
1.LINEAR SEARCH
2.BINARY SEARCH
3.EXIT
3
Exiting….