Find lower vector value recursively

Asked

Viewed 2,641 times

2

My recursive function needs to return the smallest vector, only it is always returning 0. What’s wrong with my logic?

My job:

int menor(int vet[], int i)  
{
int m=0;

if(vet[i] == 0)
{
    m=vet[i];
    return m;
}

if( vet[i] < m)
{
    m=vet[i];

}

return menor(vet,i-1);

}

int main()
{
int vetor[]= {1,2,3,5,7,11,13,17};

m=menor(vetor,7);

printf("%d\n",m );
return 0;
}

2 answers

5

What is happening is that you are zeroing the value of m with each iteration, soon will always return m=0. An alternative is to m a function parameter, passed every iteration. It would look like this:

#include <stdio.h>

int menor(int vet[], int i, int m) {
  // Se tiver chegado já ao fim do array para o código
  if(i < 0) {
    return m;
  }
  // Verifica se o valor atual é menor que o MENOR valor salvo até então
  if(vet[i] < m) {
    m = vet[i];
  }
  // Chama a recursão
  return menor(vet, i-1, m);
}

int main() {
  int vetor[]= {8,2,3,5,7,11,13,17};
  // Adicionamos um parâmetro na chamada, no caso o último valor do vetor.
  int m = menor(vetor, 7, vetor[7]);
  printf("%d\n",m);
  return 0;
}

Note that we start with a kick, which belongs to the vector, of the lowest value instead of starting with a predefined value. The way you had done may lead to unexpected behaviors, for example, and if no value is less than 0? 0 would be returned and might not even belong to the sought vector.

  • Got it, I was always zeroing, thanks bro.

2


You can implement a function that takes an integer vector and its respective size and returns the smallest finding value within this vector, see only:

int menor( int vec[], int tam )
{
    if( tam == 1 )
        return vec[0];

    int m = menor( vec + 1, tam - 1 );

    return ( vec[0] < m ) ? vec[0] : m;
}

Testing:

#include <stdio.h>

int menor( int vec[], int tam )
{
    if( tam == 1 )
        return vec[0];

    int m = menor( vec + 1, tam - 1 );

    return ( vec[0] < m ) ? vec[0] : m;
}

int main( void )
{
    int vetor[]= {8,3,5,7,11,13,17,4,8,10};
    int tam = sizeof(vetor) / sizeof(int);

    int min = menor( vetor, tam );

    printf( "%d\n", min );

    return 0;
}

Exit:

3

See working on Ideone.com

Browser other questions tagged

You are not signed in. Login or sign up in order to post.