hello i'm trying sort double linked list in c using bubble sort algorithm. here code:
struct node { unsigned char key; unsigned char num; struct node *left; struct node *right; }; here sort funcion:
void sort(int count, struct node *t_node) { struct node *tmp,*nextnode, *node1, *node2; for(node1 = t_node;node1->right != null ;node1 = node1->right) { for(node2 = node1->right; node2->right != null; node2 = node2->right) { if(node2->key > node2->right->key) { nextnode = node2->right; tmp = node2->left; node2->right = nextnode->right; node2->left = nextnode->left; nextnode->right = node2; nextnode->left = tmp; } } } } it works in 80% because example data:
node1 key=3 node2 key=144 node3 key=49 node4 key=207 the result after sort is:
node1 key=3 node2 key=144 node4 key=207 why third node disappeared? problem?
it's double-linked list. swap 2 nodes, typically 6 pointers need updated. have a <-> b <-> c <-> d , want swap b , c: you'll need update right of a, b, , c, , left of b, c, , d.
your code updating 4 pointers here:
if(node2->key > node2->right->key) { nextnode = node2->right; tmp = node2->left; node2->right = nextnode->right; node2->left = nextnode->left; nextnode->right = node2; nextnode->left = tmp; } this shall fix issue:
if(node2->key > node2->right->key) { nextnode = node2->right; tmp = node2->left; if (tmp) tmp->right = nextnode; if (nextnode->right) nextnode->right->left = node2; node2->right = nextnode->right; node2->left = nextnode->left; nextnode->right = node2; nextnode->left = tmp; }
Comments
Post a Comment