Bubble Sort improved

Asked

Viewed 729 times

-3

Although it has followed pseudocode correctly, the program is not ordering the array correctly. Why?

#include <bits/stdc++.h>

void bubbleSortM( int A[], int n ) 
{  
  int i,j,aux; 
  bool troca; 

  for(i=1; i<n; i++)
  troca = 0;

  for(j=n-1; j>=i ;j--) 
{  
if(A[j-1] > A[j]) 
  {    
 aux= A[j-1]; 
 A[j-1] = A[j]; 
 A[j] = aux; 
 troca = 1; 
   }
}
 if( !troca )
  {
return;
  }
  return;
}
void printVetor(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);

}



int main()
{
int A[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(A)/sizeof(A[0]);

bubbleSortM(A, n);

printf("Vetor ordenado: \n");
printVetor(A, n);
}
  • Can someone help me with the error of this program.

  • 2

    What error? Edit your question to include the error and take the time to fix the formatting (select the code snippet and press <ctrl> + k)

  • the program is not ordering, in the same way that the vector is inserted it exits without ordering

1 answer

4


First, watch out for the identation of your program, which is horrible. It helps others (and also yourself) to understand it. If you had done that, you’d see that one was missing { after the first for and the } corresponding before the end of the function, and that because of this, it does nothing of what you wanted.

In addition, it is good practice in C to declare variables only when they are used in the smallest possible scope. C is not Pascal that requires variables to be declared at the start of the function.

Another detail is bits/stdc++.h is a C++ header, not C. For C, use stdio.h and stdbool.h.

And there’s also a return remaining at the end of bubbleSortM which is unnecessary, since it is the last thing in the function.

Your corrected program looks like this:

#include <stdio.h>
#include <stdbool.h>

void bubbleSortM(int A[], int n) {  
    for (int i = 1; i < n; i++) {
        bool troca = 0;

        for (int j = n - 1; j >= i; j--) {  
            if (A[j - 1] > A[j]) {
                int aux = A[j - 1];
                A[j - 1] = A[j];
                A[j] = aux;
                troca = 1;
            }
        }
        if (!troca) {
            return;
        }
    }
}

void printVetor(int A[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", A[i]);
    }
}

int main() {
    int A[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(A) / sizeof(A[0]);
    bubbleSortM(A, n);
    printf("Vetor ordenado: \n");
    printVetor(A, n);
}

See here working on ideone.

Browser other questions tagged

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