Reputation: 19
Im working on a project for school in which I need to sort a linked list with any sorting algorithm (preferably bubble) - please note that swapping each node data is not allowd as I am expected to swap the nodes. I can not paste all the code of my project as it is very wide and it is in Spanish, reason for which I will show you the parts in which I try to implement the node swapping.
To sum up, the project itself is quite simple, a linked list where each node contains information of a person (name, last name, age, etc).
I have to sort the list alphabetically. Please, bear in mind that I cannot implement the sorting nor the swapping algorithms in functions (That is to say, I cannot make a 'swapNodes' function and them implement it in the code.
I managed to swap two nodes following this logic:
firstNode = auxiliar->next;
auxiliar-> next = firstNode->next;
firstNode->next = auxiliar;
This works to swap 2 nodes perfectly.
Problem is when I have to implement this logic with a sorting algorithm in order for it to sort all the list, and this is where I need you guys to help me.
I have checked every post about bubblesorting and node swapping but I just can get it working.
My professor tried to help me, implementing my node swapping code in the following way (please note that as an example, the following code should sorts by age):
while (flag == 1) {
auxiliar = firstNode;
flag = 0;
if (auxiliar->edad > auxiliarSiguiente->edad) {
firstNode = auxiliar->next;
auxiliar-> next = firstNode->next;
firstNode->next = auxiliar;
flag = 1;
}
auxiliar3 = firstNode;
while (auxiliar->next != NULL ) {
if (auxiliar->age > auxiliarNext->age) {
auxiliar2 = auxiliar->next;
auxiliar->next = auxiliar2->next;
auxiliar2->next = auxiliar;
auxiliar3->next = auxiliar2;
} else {
auxiliar = auxiliar->next;
}
auxiliar3 = auxiliar3->next;
}
}
And then again, this code works just fine when there are 2 nodes. In case there are more, it does not sort in a correct way. Moreover, Im not quite sure which sorting algorithm my professor used.
Perhaps what my teacher did is wrong, or maybe there is a simpler way to do it.
I greatly appreciate your feedback, as I could not manage to find a way to solve it myself.
Hope you guys can help me!
Upvotes: 0
Views: 1141
Reputation: 49803
Your original swap code does not alter the next
pointer of the node that pointed to the node auxiliar
pointed to before the swap (which there will be if auxiliar
isn't the first node in the list).
Upvotes: 1