r/AskComputerScience • • Nov 10 '19

Need help... Hello I'm a new computer science student. I am really confused. Is this really an insertion sort on a linked list/using pointers. Thank you everyone :)

Post image
37 Upvotes

3 comments sorted by

14

u/dhananjay1438 Nov 10 '19

This is not insertion sort. This linked list is already sorted. What happening here is we are adding new node according to its value is If node to be entered is smaller than first node we are making new new node as first node. If node(or data) to be entered is greater than that of first node then we are traversing until we don't find node which is greater than node we are trying to add. If no node is greater than the node we are trying to add then the node will be added at last!

10

u/not-just-yeti Nov 10 '19

So that function is insert, which is the workhorse for insertion-sort ( and is also useful in its own right, for adding to an already- sorted list).

5

u/manias Nov 10 '19

This code inserts a new node into an already sorted list, while keeping it sorted. Here is a nicer implementation of that:

struct node **ptr  = &head;
while(*ptr && (*ptr)->data < data) ptr = &((*ptr)->next);
struct node *newNode = (struct node *) malloc(sizeof(struct node));
newNode->next = *ptr;
newNode->data = data;
*ptr = newNode;