Bubble Sort in C inconsistent

Asked

Viewed 64 times

-1

I’m trying to create the basic structure for a program that uses Bubble Sort. However, when testing its basic structure, I see that the final vector is not being returned correctly.

#include <stdio.h>
#define TAMANHO 5

int main() {

    int vetor[TAMANHO-1],n1,n2,ctr,ctrInt;

    for(ctr=0;ctr<TAMANHO;ctr++) scanf("%d",&vetor[ctr]);

    for(ctr=0;ctr<TAMANHO;ctr++){
        for(ctrInt=0;ctrInt<TAMANHO-ctr-1;ctrInt++){
        n1=vetor[ctrInt];
        n2=vetor[ctrInt+1];
            if(n1>n2){
                vetor[ctrInt]=n2;
                vetor[ctrInt+1]=n1;
            }
        }
    }

    for(ctr=0;ctr<TAMANHO;ctr++) printf("%d",vetor[ctr]);

    return 0;
}
  • And the exchange of values is not right either. To exchange two values Voce needs a temporary variable.

1 answer

0


    int vetor[TAMANHO],n1,n2,ctr,ctrInt;

You must put in the array declaration the number of elements you want and not the last element’s input, ie to have an array with TAMANHO elements you must declare int vetor[TAMANHO].

  • But in this case, I wouldn’t have SIZE+1 terms, since vectors start with the term number 0?

  • 1

    @Nucleus values continue going from 0 to SIZE - 1, but in the array declaration is expected the number of elements, not the largest element’s input, you can read more here. Sorry for the documentation in English.

  • Do not confuse the size of the array with the variation of the index used to access a certain array position. For example. int x[3]; defines an array of 3 positions and each element will use an index between 0 and 2: x[0], x[1] and x[2].

Browser other questions tagged

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