Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
const char *data;
} Test;
int main() {
Test **array = malloc(3 * sizeof(Test *));
(*(array)) = malloc(sizeof(Test));
(*(array))->id = 3;
(*(array))->data = "3";
(*(array + 1)) = malloc(sizeof(Test));
(*(array + 1))->id = 2;
(*(array + 1))->data = "2";
(*(array + 2)) = malloc(sizeof(Test));
(*(array + 2))->id = 1;
(*(array + 2))->data = "1";
int i;
for(i=0; i<3; i++) {
printf("%s ", (*(array + i))->data);
}
for(i=1; i<3; i++) {
int j;
for(j=i; j>-1; j--) {
if(((*(array + i))->id) < ((*(array + j))->id)) {
Test *tmp = *(array + i);
*(array + i) = *(array + j);
*(array + j) = tmp;
}
}
}
printf("\n");
for(i=0; i<3; i++) {
printf("%s ", (*(array + i))->data);
}
return 0;
}
Can anyone guess?
Is there something wrong with its algorithm or code?
The output should be: 1 2 3
But it is: 2 1 3
?