0

I'm trying to use recursion to find the minimum integer in an array.

This is my code:

int minArray(int* array, int size){
    if (size == 0){
        return array[0];
    }
    int min = array[0];
    if (min > minArray(array+1,size-1)){
        min = minArray(array+1,size-1);
    }
    return min;
}

What is wrong with it? If i call the function on {1,2,3,4,5}, it will return 0.

2
  • First thing that's wrong is that recursion is the wrong approach to this task... Commented May 3, 2016 at 3:00
  • @keshlam i'm only doing it for practice with recursion Commented May 3, 2016 at 3:01

2 Answers 2

6

The condition is wrong. An array of zero elements has no elements, so accessing array[0] of it is illegal.

Also calling the function twice in this function should be avoided.

Try this:

int minArray(int* array, int size){
    if (size == 1){
        return array[0];
    }
    int min = array[0];
    int candidate = minArray(array+1,size-1);
    if (min > candidate){
        min = candidate;
    }
    return min;
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Danny, please note that the function is going to lead to UB if size is zero.
@RSahu so should i add if (size == 0) return 0; ?
@Danny, if you can, avoid calling the function if size is zero. When size is zero, how do you define minimum?
0

This solution is similar to the one of @MikeCat. I added the iterative version just for comparison purposes.

int min( int str[], int size)
{
  if (1==size)  // base case
  return str[0];
 else {
  int minor=min(&str[1],size-1); // each time the function is called its receives an array with an element less than the previous call.
  return str[0]<=minor ? str[0] : minor;
  }
}


// iterative approach. I have added the minor´s position indicator.
int mini(int str[], int size, int* position)
{
 int minor=str[0];
 for (int i=1;i<size;i++)
  if (str[i]<minor) {
   minor=str[i];
   *position=i;
   }
 return minor;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.