The linked list contain two types of data - int count and float rank. The list needs to be sorted in descending order based firstly on count and then on rank. I have sorted the list based on count, but it appears I don't get the process completely.
I understand that if current count is equal to the next count, then compare rank and insert node with higher rank.
I have changed the code after the comment, however it does output data correctly (does not sort by the rank). How can I fix it?
Sorted list by the first parameter (what I currently get):
2, 0.152009
2, 0.077676
2, 0.092575
2, 0.157685
1, 0.262355
1, 0.184311
1, 0.073388
Expected output after sorting list by the second parameter:
2, 0.157685
2, 0.152009
2, 0.092575
2, 0.077676
1, 0.262355
1, 0.184311
1, 0.073388
My code:
typedef struct node {
int count;
float rank;
struct node *next;
} NodeT;
void insertionSort(NodeT **head) {
NodeT *sorted = NULL;
NodeT *current = *head;
while (current != NULL) {
NodeT *next = current->next;
sortedInsert(&sorted, current);
current = next;
}
*head = sorted;
}
void sortedInsert(NodeT **head, NodeT *new) {
NodeT *current;
if (*head == NULL || (*head)->count <= new->count) {
new->next = *head;
*head = new;
} else {
current = *head;
while (current->next != NULL) {
/* Should second parameter check go here? */
if (current->next->count > new->count) {
current = current->next;
} else if (current->next->count == new->count) {
while (current->next != NULL && current->next->rank > new->rank) {
current = current->next;
}
}
}
new->next = current->next;
current->next = new;
}
}