The following program utilizes the Divide and Conquer paradigm and uses the idea of Merge Sort to find the maximum and minimum element of an array recursively. This was an assignment that asked to do it recursively, I've coded the solution but my question is does it minimize the number of comparisons necessary to find the values of a minimum and maximum?
#include <stdio.h>
#include <limits.h>
void max(int *ptr, int lower, int upper, int *maximum, int *min)
{
//returns the maximum element of the array
int mid;
int left, right;
if(lower == upper){
if(ptr[lower] > *maximum)
{
*maximum = ptr[lower];
}
if(ptr[lower] < *min)
{
*min = ptr[lower];
}
return;
}
mid = (lower+upper) /2;
max(ptr, lower, mid, maximum, min);
max(ptr, mid+1, upper, maximum, min);
}
int main()
{
int n;
int i;
int *ptr;
int maximum=-1;
int minimum=INT_MAX;
printf("\nEnter the size of the array : ");
scanf("%d", &n);
ptr = (int *) malloc(sizeof(int)*n);
printf("Enter the contents of the array : ");
for(i=0 ; i<n; i++)
scanf("%d", &ptr[i]);
max(ptr,0,n-1,&maximum,&minimum);
printf("\n Maximum element is : %d", maximum);
printf("\n Minimum element is : %d", minimum);
free(ptr);
return 0;
}