Search code examples
csortinglinked-listbubble-sort

Bubble Sorting Linked List


I have worked out a sorting function with a helper swapper(). The function sorts nodes in the list by their address in memory in descending order (highest address to lowest address).

The function sorts fine as long as the head of the list does not change, but when the head changes, all that returns is the head and whatever was after it. Somewhere I am losing the rest of the list and I can't figure it out.

My function so far:

void swapper(NODE *left, NODE *right)
{
    if(left->prev)
        left->prev->next = right;
    if(right->next)
        right->next->prev = left;

    left->next = right->next;
    right->prev = left->prev;

    right->next = left;
    left->prev = right;
}
NODE *sort_nodes(NODE *head)
{
    NODE *new_second, *new_first, *list = head;
    int swaps;
    do{
        swaps = 0;
        while(list)
        {
            if(&(*list) < &(*(list->next)))
            {
                swapper(list, list->next);
                swaps = 1;
            }
            list = list->next;
        }
        list = head;
    }while(swaps);
    return list;
}

Example output if the head of the list is the third node declared in the list:

Unsorted: 0x93657050 -> 0x936570d0 -> 0x93657070 -> 0x93657090 -> 0x93657030 -> 0x936570b0 -> 0x93657010 -> NULL
Sorted:   0x93657050 -> 0x93657030 -> 0x93657010 -> NULL

Solution

  • It's simple when you think about it.

    You have

    head -> A -> B
    

    Then you swap A and B without changing head, so you get

    head -|
          v
     B -> A
    

    If you swap the head element, you need to move the head pointer to the new head.