Find the smallest value in vector recursively

2

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

My role:

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;
}
    
asked by anonymous 29.06.2018 / 19:34

2 answers

2

You can implement a function that receives a vector of integers and their respective size and returns the smallest value found within this vector, see:

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;
}

Output:

3

See working at Ideone.com

    
29.06.2018 / 20:57
5

What is happening is that you are zeroing the value of m with each iteration, so it will always return m=0 . An alternative is to make m a function parameter, passed at each 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;
}

Notice that we start with a kick, which belongs to the vector, of the smallest value instead of starting with a predefined value. Could the way you did it lead to unexpected behaviors, for example, and if no value were less than 0? 0 would be returned and could not even belong to the searched vector.

    
29.06.2018 / 19:45