user3393266 user3393266 - 1 year ago 104
C Question

Recursively splitting an array in C

I'm trying to come up with a divide-and-conquer algorithm for finding the minimum element in an array but recursive code is a bit mind bending to me.

For example, taking the following pseudo code:

procedure R_MIN (A, n)
if (n = 1) then
min := A[0];
lmin := R_MIN (A, n/2);
rmin := R_MIN (&(A[n/2]), n - n/2);
if (lmin < rmin) then
min := lmin;
min := rmin;
return min;
end R_MIN

The way I understand it is we split the array in half, unless we have the base case. Then we figure out which half has the min and repeat the call, further splitting it (now we have 4 arrays). But where and how is the min actually found and what would this code look like in C? It seems to me this would only work when we have split into pairs.

Answer Source

It finds the minimum from the previous recursive calls on the left and right halves of the array. When the base case is reached and the array has length 1, then that is the minimum of that sub-array of length 1. This minimum is then taken and compared with the minimum of the other half. The lower of the two is the minimum of this sub-array. This is returned to be compared and so on...

If you translate the pseudo-code to C:

#include <stdio.h>

int rec_min(int A [],int len)
  int min,lmin,rmin;
    return A[0];
      return lmin;
      return rmin;

int main()
  int test [10]={3,2,7,4,5,8,1,9,6,10};


  return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download