Why is my array not ordered? (Bubble Sort)

-1

I've fed the array with the user input, but the algorithm does not output it in an orderly way, what did I do wrong?

    int main()
    {

// variáveis
        int vetor[5] = {0};
        int aux, i=0, j=0;
            printf("Entre com  numeros\n\n");

// input    
            for(int i=0;i<5;i++){
                scanf("%i", & vetor[i]);
            }

//Ordenação    
           for(i=0;i<5;i++){
                for(int j=0;j<(5-1);j++){
                    if(vetor[j] > vetor[j++]){
                        aux = vetor[j];
                        vetor[j] = vetor[j++];
                        vetor[j++] = aux;
                    }
                }

            }

//Output  
            for(int i=0;i<5;i++){
                printf("%i\t",vetor[i]);
            }


        return 0;
    }
    
asked by anonymous 21.09.2018 / 03:17

1 answer

1

No if that you have in the sort order is using j++ to access the following element:

if(vetor[j] > vetor[j++]){
//                    ^--
   aux = vetor[j];
   vetor[j] = vetor[j++];
//                    ^--
   vetor[j++] = aux;
//         ^--
}

This modifies the value of j permanently. So you're increasing j multiple times for each iteration, actually or 2 times or 4 times, depending on whether or not you enter within if . The correct is to access the next one without modifying j doing j + 1 :

//Ordenação
for(i=0;i<5;i++){
    for(j=0;j<(5-1);j++){
        if(vetor[j] > vetor[j+1]){
            aux = vetor[j];
            vetor[j] = vetor[j+1];
            vetor[j+1] = aux;
        }
    }
}

Code working on Ideone

It may be a good idea to also review a little how the ++ and -- works both in pre and post increment.

    
21.09.2018 / 12:33