C linkedlist bubble sort error. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; } }

16th Jun 2019, 9:19 PM
Maxim Schiffmann
Maxim Schiffmann - avatar
1 Answer
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; } }
20th Jun 2019, 7:48 AM
Volker Milbrandt
Volker Milbrandt - avatar