Educational Blog: Divide and Conquer

Tuesday, 3 March 2015

Divide and Conquer

#include<stdio.h>
 
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

int tempmax, tempmin;

int* maxmin(const int list[], const int low, const int high, int max, int min)
{
    int mid,max1,min1;
    static int maxAndMin[2]; // to hold the max and min value of list
 
    if (low == high)
    {
        max = list[low];
        min = list[low];
    }          
    else if (low == high-1)
    {
        if (list[low] < list[high])
        {
            tempmax = getMax(tempmax, list[high]);
            tempmin = getMin(tempmin, list[low]);
        }
        else
        {
            tempmax = getMax(tempmax, list[low]);
            tempmin = getMin(tempmin, list[high]);
        }
    }
 
   else
   {
       mid = (low + high) / 2;
       max1 = list[mid+1];
       min1 = list[mid+1];
       maxmin(list, low, mid, max, min);
       maxmin(list, mid+1, high, max1, min1);
       tempmax = getMax(tempmax, max1);
       tempmin = getMin(tempmin, min1);
   }
 
    maxAndMin[0] = tempmax;
    maxAndMin[1] = tempmin;
    return maxAndMin;
}
 
int getMax(int first, int second)
{
    return first > second ? first : second;
}
 
int getMin(int  first, int second)
{
    return  first < second ?  first : second;
}
 
int main(void)
{
    int list[] = {10, 23, 24, 56, 67, 78, 90};
    int *values;
    int size = ARRAY_SIZE(list);
 
    tempmax = tempmin = list[0];
    values = maxmin(list, 0, size-1, list[0], list[0]);
 
    printf("The maximum value is = %2d \n", *values);
    printf("The minimum value is = %2d \n", *(values+1));
    return 0;
}

No comments:

Post a Comment