+ 3
C linkedlist bubble sort error.
This bubble sort is deleting names, instead of sorting them. What did i wrong? void sort2(Person **anchor) { printf("\nSort! \n"); Person *second = *anchor; while(*anchor != NULL) { second = (*anchor)->next; while(second != NULL) { if(compare(*anchor, second) > 0) { Person *temp = *anchor; *anchor = second; second = temp; } second = second->next; } anchor = &(*anchor)->next; } }
1 Resposta
0
What is the declaration of Person? If it is a linked list, there will be a pointer to the next Person and some relevant content like name in. You then need to compare the content and only change the best pointers. Some untested code fragment:
struct Person {
... // content
Person *next;
};
Person *act=*anchor;
Person *prev = **anchor;
while (act != NULL && act->next != NULL) {
if (compare(act, act->next)) {
prev = act->next;
act->next = act;
act = prev->next;
}
}