Linked List Sorting
Apr 26, 2012 at 2:12pm UTC
I have to sort my linked list according to
.
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
Apr 26, 2012 at 3:32pm UTC
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 "->".
Apr 27, 2012 at 9:17am UTC
After i change the
to
.
The sorting code is still not working.
Apr 27, 2012 at 12:18pm UTC
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 Apr 27, 2012 at 12:31pm UTC
Topic archived. No new replies allowed.