• Advertisement
Sign in to follow this  

Find Min with Recursion

This topic is 1448 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I wouldn't like that solution as it scans the data many times. You might as well just have an iterative solution at that point. Also, there is a bug, if the function is passed a one element array, the index is not set.

 

A nicer solution might be to change the signature to accept a range:

double recursive_min(double *array, int start, int end, int *index);

Here, end is "one past the end", i.e. for an array of size N, end would be N.

 

So now, in the recursion, pass the same array (no pointer arithmetic), but modify the start / end parameters appropriately. Thus, you would then always know the absolute index even as you go deeper in the recursion.

Share this post


Link to post
Share on other sites
Advertisement
rip-off's suggestion is good.

Alternatively, you can keep the original signature, if you are a little bit careful:

double recursive_min(double *data, unsigned n, unsigned *index) {
  if (n==1) {
    *index = 0;
    return data[0];
  }

  unsigned index_left, index_right;
  double left = recursive_min(data, n/2, &index_left);
  double right = recursive_min(data + n/2, n - n/2, &index_right);

  return left < right ? (*index = index_left, left) : (*index = index_right + n/2, right);
}

Share this post


Link to post
Share on other sites

Note that returning the index instead of the value can be a good solution. You can handle an empty array by returning an invalid index, such as -1 or N, but client code can still quickly get the value by using the index. For more general searching algorithms, this can handle the case where no matching element is found, too.

Share this post


Link to post
Share on other sites

thanks :)

 

Is it necessary to have 2 different index?

Because I think this also works too. 

double recursive_min(double T[], int n, int *index){
	if (n == 1){
		*index = 0;
		return T[0];}
	else{
		double x = recursive_min(T, n/2, index);
		double y = recursive_min(T + n/2, n - n/2, index);
		if (x < y){
			return x;}
		else {
			*index = *index + n/2;
			return y;}
	}
}

Share this post


Link to post
Share on other sites

Yes, returning the index is a good solution:

unsigned recursive_min(double *data, unsigned n) {
  if (n <= 1) // [EDIT: Was `n == 1'. Thanks, rip-off.]
    return n - 1; // returns -1 for an empty input
  unsigned left_index = recursive_min(data, n/2);
  unsigned right_index = recursive_min(data + n/2, n - n/2) + n/2;
  return data[left_index] < data[right_index] ? left_index : right_index;
}
Edited by Álvaro

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement