C program for Linear search and Binary search
#include <stdio.h>
#include <stdlib.h>
void enterelements(int a[],int size)
{
int i;
for(i=1;i<=size;i++)
{
printf("\nEnter element%d: ",i);
scanf("%d",&a[i]);
}
}
void linear_search(int a[],int item,int size)
{
int flag=0,i;
for(i=0;i<=size;i++)
{
if(a[i]==item)
{
printf("\nElement found at position %d",i);
flag=1;
}
}
if(flag==0)
{
printf("\nElement not found!");
}
}
void binary_search(int a[],int item,int size)
{
int i=0,mid,l=1,u=size+1,flag=0;
while((flag!=1)&&(i<=u))
{
mid=(l+u)/2;
if(a[mid]==item)
{
printf("\nElement found at position %d",mid);
flag=1;
}
if(item<mid)
{
u=mid-1;
}
else
{
l=mid+1;
}
i++;
}
if(flag==0)
{
printf("\nElement not found!");
}
}
int main()
{
int a[100],i,j,size,ch,item;
printf("\nEnter the size of array: ");
scanf("%d",&size);
enterelements(a,size);
printf("\nElements in array are: ");
i=1;
while(i<=size)
{
printf(" %d",a[i]);
i=i+1;
}
do
{
printf("\n\n..MENU..\n1. Linear Search\n2. Binary Search\n3. Exit\n\nEnter your choice: ");
scanf("%d",&ch); switch(ch)
{
case 1: printf("\nEnter the item to be searched: ");
scanf("%d",&item);
linear_search(a,item,size);
break;
case 2: printf("\nEnter the item to be searched: ");
scanf("%d",&item);
binary_search(a,item,size);
break;
case 3: exit(0);
default:printf("\nWrong choice!");
}
}while(1);
}
#include <stdlib.h>
void enterelements(int a[],int size)
{
int i;
for(i=1;i<=size;i++)
{
printf("\nEnter element%d: ",i);
scanf("%d",&a[i]);
}
}
void linear_search(int a[],int item,int size)
{
int flag=0,i;
for(i=0;i<=size;i++)
{
if(a[i]==item)
{
printf("\nElement found at position %d",i);
flag=1;
}
}
if(flag==0)
{
printf("\nElement not found!");
}
}
void binary_search(int a[],int item,int size)
{
int i=0,mid,l=1,u=size+1,flag=0;
while((flag!=1)&&(i<=u))
{
mid=(l+u)/2;
if(a[mid]==item)
{
printf("\nElement found at position %d",mid);
flag=1;
}
if(item<mid)
{
u=mid-1;
}
else
{
l=mid+1;
}
i++;
}
if(flag==0)
{
printf("\nElement not found!");
}
}
int main()
{
int a[100],i,j,size,ch,item;
printf("\nEnter the size of array: ");
scanf("%d",&size);
enterelements(a,size);
printf("\nElements in array are: ");
i=1;
while(i<=size)
{
printf(" %d",a[i]);
i=i+1;
}
do
{
printf("\n\n..MENU..\n1. Linear Search\n2. Binary Search\n3. Exit\n\nEnter your choice: ");
scanf("%d",&ch); switch(ch)
{
case 1: printf("\nEnter the item to be searched: ");
scanf("%d",&item);
linear_search(a,item,size);
break;
case 2: printf("\nEnter the item to be searched: ");
scanf("%d",&item);
binary_search(a,item,size);
break;
case 3: exit(0);
default:printf("\nWrong choice!");
}
}while(1);
}
No comments