Algorithm of Division and Conquest

Asked

Viewed 100 times

0

I’m having trouble making a division and conquest algorithm of the sum of the elements of an arrangement.

public static int somatorio(int[] a, int numElem) {
    if(numElem == 0) {
       return 0;
    }else if(numElem == 1){
       return a[0];
    }

    int meio = numElem/2;
    int dTamanho = numElem - meio; //tamanho lado direito
    int eSoma = somatorio(a, meio); //soma lado esquerdo
    int dSoma = somatorio(a, dTamanho); //soma lado direito

    return eSoma + dSoma;
}

I’m not able to perform this sum recursively, how can I fix my code?

  • First, it has no division and no conquest, it has division, it has complication and it does the same thing as not divided. Second: because it does not iterate that much easier, and without division?

  • College job ahhahah. I’m having a hard time with this part.... would then have some tip on how to improve this code or where I can get information?

1 answer

1

UPDATE: I managed to solve my problem, in case someone is also in doubt I will leave my code

public static int somatorio(int[] a, int inicio. int fim) {
     if(inicio == fim) {
        return a[inicio];
     }else
        if(inicio == fim-1) {
           return a[inicio] + a[fim];
        }else {
           int meio = (fim + inicio)/2;
           int eSoma = somatorio(a, inicio, meio); //soma lado esquerdo
           int dSoma = somatorio(a, meio+1, fim); //soma lado direito

           return eSoma + dSoma;
        }
}

Browser other questions tagged

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