Linked List Sorting

I have to sort my linked list according to
int id
.
The each node in linked list contain:

string name
int id
int salary


This is my wrong sorting code:

void LinkedList::sortByID()
{
     LinkedList *current; 
     
     for(int i=1; i<size; i++)
     {
        current = head;
        for(int i = 0; i < size-1 ;i++)
        {
           if(current->id > current->next->id)
           {
              LinkedList *temp = new LinkedList;

              temp->name = current->name;
              temp->id = current->id;
              temp->salary = current->salary;

              current->name = current->next->name;
              current->id = current->next->id;
              current->salary = current->next->salary;
              
              current->next->name = temp->name;
              current->next->id = temp->id;
              current->next->salary = temp->salary;
              
              current = current->next;
              delete temp;
           }
        }
     }
}


After tested, it only able to swap first two node data only.
Why?
Any other method to implement sorting much easier?
Can provide some example for those other method?

Any help will be appreciate.
Thanks
Hmm, thought that wouldn't compile. You use the variable name 'i' in both loops. Change the 2nd one to 'j'. Also, you can remove a few lines by changing
1
2
3
4
5
6
7
              LinkedList *temp = new LinkedList;

              temp->name = current->name;
              temp->id = current->id;
              temp->salary = current->salary;
              ...
              delete temp


to

 
LinkedList temp(*current);  


though you will need to access its data mambers with "." instead of "->".
After i change the
int i
to
int j
.
The sorting code is still not working.
if you add this to your class:
1
2
3
4
bool operator<(LinkedList* a)
{
       return id<a->id;
       }

and
1
2
3
4
5
6
7
8
void swap(LinkedList* a, LInkedList* b)
{
       swap(a->id, b->id);
       swap(a->name, b->name);
       swap(a->salary, b->salary);
       swap(a->size, b->size);
       if (a->next!=NULL && b->next!=NULL) swap(a->next, b->next);
       }

you should be able to sort it with std::sort.
Last edited on
Topic archived. No new replies allowed.