3.Write a C Program to search an element using linear search technique and recursive binary search technique.
#include < stdio.h>
#include < stdlib.h>
main()
{
int array[100],search_key,i,j,n,low,high,location,choice,result;
void linear_search(int search_key,int array[100],int n);
clrscr();
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<= n;i++)
{
scanf("%d",&array[i]);
}
printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key);
printf("___________________\n");
printf("1.LINEAR SEARCH\n");
printf("2.BINARY SEARCH\n");
printf("___________________\n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&choice);
switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
result = binaryScr(array, 0, n, search_key);
if(result == -1)
{
printf("______________________________________\n");
printf("The element is not present in array");
}
else
{
printf("______________________________________\n");
printf("The element is present at index %d",result);
}
break;
default:
exit(0);
}
getch();
return 0;
}
/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{
int i,location;
for(i=1;i< =n;i++)
{
if(search_key == array[i])
{
location = i;
printf("______________________________________\n");
printf("The location of Search Key = %d is %d\n",search_key,location);
}
}
}
/* BINARY SEARCH */
int binaryScr(int a[], int low, int high, int m)
{
if (high >= low) {
int mid = (low + high) / 2;
if (a[mid] == m) {
return mid;
}
else if(a[mid] > m) {
return binaryScr(a, low, mid - 1, m);
}
else
{
return binaryScr(a, mid + 1, high, m);
}
}
return -1;
}