Search code examples
csortinglinked-listbubble-sort

Bubble sort linked list


I have these two structs that are building an linked list:

struct Element {
    int value;
    struct Element *next;
};

struct List {
    struct Element *first;
};

Now I want to sort the linked list with a bubble sort. I implemented the method sortList that compares the value of the current element with the value of the next element. If the value of the next element is bigger than the current one they have to swap. But at this moment it doesn't work correctly.

void sortList(List *list) {
    Element *current = malloc(sizeof(Element));
    current = list->first;
    Element *nextElement = malloc(sizeof(Element));
    nextElement = current->next;
    Element *tmp = malloc(sizeof(Element));
    tmp = NULL;

    int changed = 1;
    while (changed) {
        changed = 0;
        for (current; (current != NULL) && (nextElement != NULL); ) {
            if (current->value > nextElement->value) {
                tmp = current->next;
                current->next = nextElement->next;
                nextElement->next = tmp;
                changed = 1;
            }
            current = current->next;
            nextElement = nextElement->next;
        }
    }
}

Solution

  • After the for,before restarting the while, you have to set current and nextElement pointing the beginning of the list! Or they dont change and the test condition of the for fail immediatly. Also, what's the point of the mallocs? you use current,next and temp only as pointer to node, not as real node, I think that you can delete all of them. And you can rewrite the for as a while with the condtion only, it's more readable. Sorry for my english.

    EDIT: as written under the question you need to change the pointer inside list. I think that the easiest way is to move the lower element at the beginning of the list immediatly, and change the the head of the list to point this element. After that sort the rest of the list.