I am writing a bubble sort function to sort nodes in a doubly linked list. My function is very close to working, but I am missing something simple and I can’t figure it out.
void sort (struct lnode** head, void (*swapPtr) (struct lnode** head, struct lnode* n1, struct lnode* n2),
int(*comparePtr) (void* v1, void* v2)) {
struct lnode* next;
struct lnode* temp = *head;
int comp;
struct lnode* temp2;
int count = 0;
while (temp != NULL) {
temp2 = nodeGetNext(temp);
temp = temp2;
count++;
}
temp = *head;
for(int i = 0; i < count; i++) {
next = nodeGetNext(temp);
comp = comparePtr(temp,next);
if (comp == 1)
swapPtr(head, temp, next);
else if (comp == -1)
swapPtr(head, next, temp);
temp = nodeGetNext(next);
}
}
When I run the function, It only swaps the first two nodes. I’m guessing I am not setting temp properly at the end of the for loop. I have tried a few different things but have not had any success. I would appreciate any help!
It seems like you make only one pass on over the list. You need to keep looping over the list and keep swapping until there’s nothing to swap. Check this answer for an example and Wikipedia for the detailed algorithm description.