'trouble with linked list bubble sort
I am a beginner learning to make bubble sort work with linked lists. I saw a geeksforgeeks page talking about this (https://www.geeksforgeeks.org/bubble-sort-for-linked-list-by-swapping-nodes/), and adapted to my circumstances. I've gotten the code to work properly, but I have trouble understanding how logic works in this sorting. To my understanding "head" acts as base point, it always indicates the first node. But to my knowledge the head pointer should always move with the node (if node a and b are swapped, and head points to a, then head would continue pointing to a, even after the swap), this seems to contradict the first statement.
here is my code:
typedef struct Node{
int Nid;
char Nname[9];
int Ngrades;
struct Node *next;
}NODE;
int bubbleSortID(NODE** head, int count){
NODE** h;
NODE* temp;
for (int i = 0; i <= count; i++) {
h = head;
for (int j = 0; j < count-1; j++) {
NODE* p1 = *h;
NODE* p2 = p1->next;
if (p1->Nid > p2->Nid) {
temp = p2->next;
p2->next = p1;
p1->next = temp;
*h = p2;
}
h = &(*h) -> next;
}
}
}
void getID(NODE *head){ //used to print result
while (head != NULL){
printf("%d %s %d \n", head->Nid, head->Nname, head->Ngrades);
head = head->next;
}
}
given input:
10355112 jack 80
10311103 tom 85
10355107 zenry 70
10355014 tim 95
10355123 mary 85
11355123 helloo 1000
expected output:
10311103 tom 85
10355014 tim 95
10355107 zenry 70
10355112 jack 80
10355123 mary 85
11355123 helloo 1000
can someone help me understand what is going on in this code?
Solution 1:[1]
To my understanding "head" acts as base point, it always indicates the first node.
Yes, but don't confuse this head variable with another variable, h, which is not intended to always (indirectly) point at the first node.
Also note that when h = &(*h) -> next; is executed, h and head are no longer the same pointer, and *h is no longer the first node of the list. h has then become the address of the next pointer of the node that precedes the node that will be referenced by p1 in the next iteration.
to my knowledge the head pointer should always move with the node (if node a and b are swapped, and head points to a, then head would continue pointing to a, even after the swap),
True, and that is why *h = p2 is executed, so that *h is guaranteed to point to the node that has the lesser value, and does not stick to what it was before the swap. This becomes the invariant after the if block: whether or not that block was executed, *h refers to the node behind the other node that was used in the comparison, and they are in their right order.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
