Bubble-sorting doubly linked list

user1630441 picture user1630441 · Jan 16, 2014 · Viewed 18.2k times · Source

I have a problem with my bubble-sorting function for the doubly linked list. It is working when I'm sorting the nodes in the singly linked way (only with ->next), but I can't make it work with ->prev pointers. Here is the code I'm using:

void sort(int count)
{
    struct data *tmp,*current,*nextone;
    int i,j;
    for(i=0;i<count;i++)
    {
        current = first;
        for(j=0;j<count-1-i;j++ )
        {
            if(current->number > current->next->number)
            {
                nextone = current->next;
                current->next = nextone->next;
                nextone->next = current;
                if(current == first)
                {
                    first = nextone;
                    current = nextone;
                }
                else
                {
                    current = nextone;
                    tmp->next = nextone;
                }
            }
            tmp = current;
            current = current->next;
        }
    }
}

And this is the structure I'm using (with the global variables for the first and last element of the list):

struct data    
{
    int id;
    char name[20];
    int number;
    struct data *next;
    struct data *prev;
};

struct data *first = NULL;
struct data *last = NULL;

Answer

Buddha picture Buddha · Jan 16, 2014

Below logic would work.

I would follow similar algorithm... If you want to move the entire nodes...

struct data *before, *after;
if(current->number > current->next->number)
{
    before = current->prev;
    after = current->next;
    if(before != NULL){
        before->next = after;
    }
    current->next = after->next;
    current->prev = after;
    after->next = current;
    after->previous = before;
}

Alternatively, you can simply swap the numbers in the nodes without bothering to move entire nodes, if sorting of the data is the purpose. You can expand the below logic to include swapping of both char array and id as well.

if(current->number > current->next->number)
{
    int tempNum = current->number;
    current->number = current->next->number;
    current->next->number = tempNum;
}