#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int searchLinear(int a[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
{
if (a[i] == x)
return (i + 1);
}
return -1;
}
int searchBinaryNR(int a[], int l, int h, int x)
{
int i, mid;
while (l <= h)
{
mid = (l + h) / 2;
if (a[mid] == x)
return (mid + 1);
else if (x > a[mid])
l = mid + 1;
else
h = mid - 1;
}
return -1;
}
int searchBinaryR(int a[], int l, int h, int x)
{
int i, mid;
while (l <= h)
{
mid = (l + h) / 2;
if (a[mid] == x)
return (mid + 1);
else if (x > a[mid])
return searchBinaryR(a, mid + 1, h, x);
else
return searchBinaryR(a, l, mid + 1, x);
}
return -1;
}
void inputArray(int a[], int n)
{
int i;
printf("
Enter array elements:");
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
}
int main()
{
int a[MAX], n, s, x, pos;
while (1)
{
printf("
Press 1 to search using Linear Search Algorithm");
printf("
Press 2 to search using Non - Recursive Binary Search Algorithm");
printf("
Press 3 to search using Recursive Binary Search Algorithm");
printf("
Press 4 to exit");
printf("
");
scanf("%d", &s);
switch (s)
{
case 1:
printf("
Enter how many elements<= %d :", MAX);
scanf("%d", &n);
inputArray(a, n);
printf("
Enter the element to be searched : ");
scanf("%d", &x);
pos = searchLinear(a, n, x);
break;
case 2:
printf("
Enter how many elements<= %d :", MAX);
scanf("%d", &n);
inputArray(a, n);
printf("
Enter the element to be searched :");
scanf("%d", &x);
pos = searchBinaryNR(a, 0, n, x);
break;
case 3:
printf("
Enter how many elements<= %d :", MAX);
scanf("%d", &n);
inputArray(a, n);
printf("
Enter the element to be searched : ");
scanf("%d", &x);
pos = searchBinaryR(a, 0, n, x);
break;
default:
exit(0);
}
if (pos != -1)
printf("
Element found at %d position", pos);
else
printf("
Element not found");
}
return 0;
}