L-18 MCS 275 Mon 19 Feb 2001
Below are the listings for the programs we discussed in class.
/* L-18 MCS 275 : binary search to locate element in integer array */
#include <stdio.h>
int rec_search (int start, int end, int a[], int i);
/* returns k, if a[k] = i, and start <= k <= end;
-1, otherwise */
int itr_search (int start, int end, int a[], int i);
/* iterative version of the recursive search */
void bin_search (int n);
/* prompts the user for n integer numbers and an element */
int main()
{
int n;
printf("Locating a number in an integer array with binary search.\n");
printf("Give number of elements : ");
scanf("%d", &n);
bin_search(n);
return 0;
}
void bin_search (int n)
{
int i, a[n], pos;
char cont = 'y';
printf("Give %d SORTED integers : ", n);
for (i=0; i < n; i++) scanf("%d", &a[i]);
printf("Your array of %d integers : ", n);
printf("%d", a[0]);
for (i=1; i < n; i++)
{
printf(" %d", a[i]);
if (a[i] < a[i-1])
{
printf("THE ARRAY MUST BE SORTED IN ASCENDING ORDER!!!\n");
return;
}
}
printf("\n");
while (cont == 'y')
{
printf("Give a number to look for : ");
scanf("%d",&i);
printf("Looking for %d in the array recursively...\n",i);
pos = rec_search(0,n-1,a,i);
printf(" the number %d ",i);
if (pos == -1)
printf("does not occur in the array\n");
else
printf("occurs at position %d\n", pos);
printf("Looking for %d in the array iteratively...\n",i);
pos = itr_search(0,n-1,a,i);
printf(" the number %d ",i);
if (pos == -1)
printf("does not occur in the array\n");
else
printf("occurs at position %d\n", pos);
printf("You want more searches ? (y/n) ");
cont = getchar();
cont = getchar();
}
}
int rec_search (int start, int end, int a[], int i)
{
int middle;
if (start == end)
if (a[start] == i)
return start;
else
return -1;
else
{
middle = (start + end)/2;
if (a[middle] == i)
return middle;
else if (a[middle] < i)
return rec_search(middle+1,end,a,i);
else
return rec_search(start,middle-1,a,i);
}
}
int itr_search (int start, int end, int a[], int i)
{
int my_start = start;
int my_end = end;
int middle;
while (my_start != my_end)
{
middle = (my_start+my_end)/2;
if (a[middle] == i)
return middle;
else if (a[middle] < i)
my_start = middle+1;
else
my_end = middle-1;
}
if (a[my_start] == i)
return my_start;
else
return -1;
}