Error in sorting numbers

Asked

Viewed 79 times

2

Even numbers I managed to sort, only odd numbers I can’t sort. The memory address of the number appears.

Link to the question: Even and Odd

Here is my code:

#include <stdio.h>
int main(int argc, char** argv)
{
    int teste, i, j, aux, aux1, c1 = 0, c2 = 0;
    scanf("%d", &teste);
    int vetor[teste], par[teste], impar[teste];
    for(i = 0; i < teste; i++)
    {
        scanf("%d", &vetor[i]);
    }
    for(i = 0; i < teste; i++)
    {
        if(vetor[i] % 2 == 0)
        {
            par[i] = vetor[i];
            c1++;
        }
        else
        {
            impar[i] = vetor[i];
            c2++;
        }
    }
    for(i = 0; i < teste - 1; i++)
    {
        for(j = i + 1; j < teste; j++)
        {
            if(par[i] > par[j])
            {
                aux = par[i];
                par[i] = par[j];
                par[j] = aux;
            }
        }
    }
    for(i=0;i<teste-1;i++)
    {
        for(j=i+1;j<teste;j++)
        {
            if(impar[i]<impar[j])
            {
                aux1=impar[i];
                impar[i]=impar[j];
                impar[j]=aux1;
            }
        }
    }
    for(i=0;i<c1;i++)
    {
        printf("%d\n",par[i]);
    }
    for(i=0;i<c2;i++)
    {
        printf("%d\n",impar[i]);
    }
    return 0;
}

1 answer

1


I believe the order goes wrong by not considering all the items.

#include <stdio.h>

int main() {
    int quantidade;
    scanf("%d", &quantidade);
    int par[quantidade], impar[quantidade], qtdePar = 0, qtdeImpar = 0;
    for (int i = 0; i < quantidade; i++)  {
        int entrada;
        scanf("%d", &entrada);
        if (entrada % 2 == 0) par[qtdePar++] = entrada;
        else impar[qtdeImpar++] = entrada;
    }
    for (int i = 0; i < qtdePar; i++) {
        for (int j = i; j < qtdePar; j++) {
            if (par[i] > par[j]) {
                int aux = par[i];
                par[i] = par[j];
                par[j] = aux;
            }
        }
    }
    for (int i = 0; i < qtdeImpar; i++) {
        for (int j = i; j < qtdeImpar; j++) {
            if (impar[i] < impar[j]) {
                int aux = impar[i];
                impar[i] = impar[j];
                impar[j] = aux;
            }
        }
    }
    for (int i = 0; i < qtdePar; i++) printf("%d\n", par[i]);
    for (int i = 0; i < qtdeImpar; i++) printf("%d\n", impar[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I would like to understand what is wrong in the answer.

  • I was wrong at the time of the odd and odd quantity, thank you for your help

Browser other questions tagged

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