Search code examples
carraysalgorithmrecursiondivide-and-conquer

To find largest and smallest elements in an array of n numbers using recursion


I am using Divide and conquer technique which reduces the array into half on each iteration. I am struct with the logic of the code.

#include <stdio.h>

void minmax(int a[], int min,int max, int l,int r)
{
    int m,min1,max1;
    if(l==r)
    {
        min=a[l];
        max=a[l];

    }

    else if((r-l)==1)
    {
        if(a[l]<=a[r])
        { 
            min=a[l];
            max=a[r];
        }
        else
        {
            min=a[r];
            max=a[l];
        }
    }

    else
    {
        m = (l+r)/2;
        minmax(a,min,max,l,m);
        minmax(a,min1,max1,m+1,r);

        if(max1>max)
            max=max1;
        if(min1<min)
            min=min1;

    }

    printf("%d \t %d\n",max,min);
}

int main(void)
{

    int a[]={12,4,32,76,34,77,24,12};
    minmax(a,a[0],a[0],0,7);
    return 0;
}

The Output of this is as follows


12   4
76   32
12   0
77   34
24   12
0    0
12   0

Desired Output


12   4
76   32
76   4
77   34
24   12
77   12
77   4

Any suggestions ? Thanks.

EDIT 1 : The algorithm


Algorithm MinMax(A[l..r], minval, maxval)
//Finds the values of the smallest and largest elements in a given subarray
//Input: A portion of array A[0..n − 1] between indices l and r (l ≤ r)
//Output: The values of the smallest and largest elements in A[l..r]
//assigned to minval and maxval, respectively
if r = l
    minval ← A[l]; maxval ← A[l]
else if r − l = 1
    if A[l] ≤ A[r]
        minval ← A[l]; maxval ← A[r]
    else 
        minval ← A[r]; maxval ← A[l]

    else //r − l > 1
        MinMax(A[l..(l + r)/2], minval, maxval)
        MinMax(A[(l + r)/2 + 1..r], minval2, maxval2)

        if minval2 < minval
            minval ← minval2
        if maxval2 > maxval
            maxval ← maxval2

Solution

  • You need to use pointers to make minmax() return anything...

    try using

    void minmax(int a[], int * min_ptr,int * max_ptr, int l,int r){
        int m,min,max,min1,max1;
    

    And before exit:

    *min_ptr=min;
    *max_ptr=max;
    return;
    }
    

    And replace all minmax calls from

    minmax(a,min,max,l,m);
    

    to

    minmax(a,&min,&max,l,m);
    

    And read something about Call by Value