Why is my array not sorted? (Bubble Sort)

Asked

Viewed 54 times

-1

I fed the array with the user input, but the algorithm doesn’t give the output in an orderly way, which I did 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;
    }

1 answer

1


In the if which you have in the ordering part you are using j++ to access the next element:

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

This modifies the value of j permanently. That is why the j several times for each iteration, actually or 2 times or 4 times, depending on whether or not you enter within the if. The correct is to access the next without modifying the j making 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 might be a good idea to also review a little how the operator works ++ and -- in both pre and post increment.

Browser other questions tagged

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