Lab_1
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void linsearch(int[],int,int); //function prototype
void binsearch(int[],int,int); //function prototype
void main()
{
int a[10],i,key,n,choice;
clrscr();
while(1)
{
printf("\n\nMENU\n");
printf("\n 1. Linear Search\n");
printf("\n 2. Binary Search\n");
printf("\n 3. Exit\n");
printf("\nEnter your choice :");
scanf("%d",&choice);
printf("\nEnter the size of the array : ");
scanf("%d",&n);
printf("\nEnter elements of the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the item to be searched : ");
scanf("%d",&key);
switch(choice)
{
case 1: linsearch(a,n,key);
break;
case 2: binsearch(a,n,key);
break;
case 3: exit(0);
default: printf("\n Wrong choice\n");
}
}
}
void linsearch(int arr[], int n, int key)
{
int i,loc=0;
for(i=0;i<n;i++)
{
if(arr[i]==key)
{
loc=i+1;
break;
}
}
if(loc==0)
printf("\n%d is not found!! Search unsuccessful",key);
else
printf("\n%d is found at location %d",key,loc);
}
void binsearch(int arr[], int n, int key)
{
int beg= 0, end = n-1, mid,loc;
while(beg<=end)
{
mid=(beg+end)/2;
if(key==arr[mid])
{
loc = mid+1;
printf("\n %d found at location %d",key,loc);
getch();
exit(0);
}
else if (key < arr[mid])
end = mid - 1;
else
beg = mid + 1 ;
}
printf("\n %d is not found in the list",key);
}