L-15 MCS 275 Mon 12 Feb 2001

Below are the listings for the programs we discussed in class.
/* L-15 MCS 275 : divide and conquer, find min and max in array */

#include <stdio.h>

void itr_minimax (int n, int a[n], int *min, int *max, int *cntcmp);
/* iterative version to compute the minimum and maximum in an array 
   of n integers, the results are returned in min and max, cntcmp
   counts the number of comparisons made */
void rec_minimax (int start, int end, int a[], int *min, int *max, int *cntcmp);
/* recursive version of the min/max calculation, in the range start..end
   of the array a; cntcmp must here be initialized to zero  */
void minimax (int n);
/* prompts the user to give in n integers and calls the iterative
   and recursive versions of the algorithms */

int main()
{
   int n;

   printf("Computing minimum and maximum of integer array.\n");
   printf("Give number of elements : ");
   scanf("%d", &n);
   minimax(n);

   return 0;
}

void minimax (int n)
{
   int i, a[n], min, max, cnt;

   printf("Give %d integers : ", n);
   for (i=0; i < n; i++) scanf("%d", &a[i]);
   printf("Your array of %d integers : ", n); 
   for (i=0; i < n; i++) printf(" %d", a[i]);
   printf("\n"); 
   printf("Computing minimum and maximum iteratively :\n");
   itr_minimax(n,a,&min,&max,&cnt);
   printf("   minimum is %d, maximum is %d\n", min, max, cnt);
   printf("   number of comparisons made is %d\n", cnt);
   printf("Computing minimum and maximum recursively :\n");
   cnt = 0;
   rec_minimax(0,n-1,a,&min,&max,&cnt);
   printf("   minimum is %d, maximum is %d\n", min, max, cnt);
   printf("   number of comparisons made is %d\n", cnt);
}

void itr_minimax(int n, int a[n], int *min, int *max, int *cntcmp)
{
   int i;
   *min = a[0];
   *max = a[0];
   *cntcmp = 0;

   for (i=1; i < n; i++)
   {
      (*cntcmp)++;
      if (a[i] > *max)
         *max = a[i];
      else 
      {
         (*cntcmp)++;
         if (a[i] < *min)
            *min = a[i];
      }
   }
}

void rec_minimax(int start, int end, int a[], int *min, int *max, int *cntcmp)
{
   int middle, min1, max1, min2, max2;

   if (start == end)
   {
      *min = a[start];
      *max = a[end];
   }
   else if (start == end-1)
   {
      if (a[start] < a[end])
      {
         *min = a[start];
         *max = a[end];
      }
      else
      {
         *min = a[end];
         *max = a[start];
      }
      (*cntcmp)++;
   }
   else
   {
      middle = (start+end)/2;
      rec_minimax(start,middle,a,&min1,&max1,cntcmp);
      rec_minimax(middle+1,end,a,&min2,&max2,cntcmp);
      if (min1 < min2)
         *min = min1;
      else
         *min = min2;
      if (max1 < max2)
         *max = max2;
      else
         *max = max1;
      *cntcmp = *cntcmp + 2;
   }
}