Search code examples
c++linked-listbubble-sort

c++ issue with bubble sort in linked list


i need some help in c++ bubble sort with linked list. I need to sort a list of int number like 55-10-50-33. I used this code

struct lista2{
    int val;
    lista2 *next;
};


void swap(int& x, int& y){
    int tmp ; tmp = x ; x = y ; y = tmp ;
}


ptr_lista2 sort (ptr_lista2 head){
    ptr_lista2 i,j;
    for(i=head; i->next!=NULL;i=i->next){
        for (j=head;j->next!=NULL;j=j->next){
            if(i->val < j->val) swap(i->val, j->val);
        }
    }
    return (head);
}

this code return 10-50-55-33. Why? Where is the error? I need 10-33-50-55!!

Thanks a lot to all!


Solution

  • It does not go to last element because the next pointer of last element is NULL ,

    You need to make "j!=nullptr;"

    You compare theese guys with themselves (it is not cause of your problem but it does not seem cool :D )

    If you want to fix it, make "j=i->next;"