How to find the largest element of a vector recursively?

Asked

Viewed 605 times

-1

I could only do it iteratively, but recursively I have no idea how to start.

  • 3

    Show that you have put effort trying to do something and edit the question, your other one has already been closed without you adding it.

1 answer

0


take a look at these links: java recursiveness, question in java forum-recursiveness.

I’m not going to make all the code for you because it would take away part of your learning, but I’ll explain how it could work.

A recursive function is a function that calls itself. So what you could do is have a function / method that checks whether a particular element of the vector is larger than the greatest-found so far.

To do this, you can have a global variable that stores the largest element of the vector, and pass the current index that is "analyzing" as a parameter in the recursive function.

A pseudo-code would look like this:

void achaMaior_recursivo(Vetor vet, Indice i){
    // se o índice atual tiver passado do último elemento do vetor, para a recursividade
    if (i >= vet.quantidadeDeElementos){
        return;
    } else {
        //se o elemento atual é o maior até agora, atualiza maiorEcontrado
        if (vet[i] > maiorEcontrado)
            maiorEncontrado = vet[i];

        //procura pelo maior elemento nos índices restantes
        achaMaior_recursivo(vet, i+1);
    }

}

Browser other questions tagged

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