1
Hey there, guys. I’m trying to solve an exercise, by bubblesorte ordering method and dynamic allocation (No pointers and no dynamic allocation the exercise becomes easier, however, the teacher asked to do with AD). The exercise is simple, is to say how many times the problem will run, pass the number of numbers to be reordered and, play on screen. Follow the code:
#include<stdio.h>
#include<stdlib.h>
main(){
int qt,n,i,j,aux;
int *p;
scanf("%d",&qt);
while(qt!=0){
scanf("%d",&n);
p = (int *) calloc(n, sizeof(int));
for(i=0; i<n; i++){
scanf("%d",(p+i));
}
/* for(i=0; i<n; i++){
printf("%d\n",*p); /* Neste for, estou testando se o ponteiro está pegando os números, e está */
++p;
} */
for(i=0; i<n-1; i++){
for(j=n-1; j>i; j--){
if(*p < *(p-1)){
aux = *p;
*p = *(p-1);
*(p-1) = aux;
}
}
}
for(i=0; i<n; i++){
printf("%d ",*p);
++p;
}
printf("\n");
free(p);
qt--;
}
}
Anyway, the error happens in the sorting method, when in the end, I print the reordered values, only garbage appears. I know I am wrong in the ordering method, I have tried to put a ++p or --p, but it has not helped. I believe that *(p-1) is wrong. Could anyone tell me the mistake? Grateful.
Thank you, Joseph X. I will follow your tips. A question, what is this method you used to order?
– Fiodor
@Fiodor is the very Bubble Sort, only that making the comparisons from the beginning and not from the end, I think it is more natural
– zentrunix