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.
Can someone help me with the error of this program.
– Carlos Ferreira
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
)– Jefferson Quesado
the program is not ordering, in the same way that the vector is inserted it exits without ordering
– Carlos Ferreira