Not able to write the code. Its getting very complex to do insertion sort with singly linked list. Help me to approach the problem and check my code. It’s giving segmentation fault.
Insertion Sort - Linked List
hi @anishanand3733, Let me share a simpler approach with you ,
ALGO :-
- Create an empty sorted list
- Traverse the given list, do following for every node.
…a) Insert current node (in a sorted way) in the sorted list. - Finally , change the head of given linked list to head of sorted (or result) list.
Now the main question is how to implement 2.( a ) part , so for that
- If Linked list is empty then make the node as
head and return it. - If the value of the node to be inserted is smaller than the value of the head node, then insert the node at the start and make it head.
- In a loop, find the appropriate node after which the input node is to be inserted. To find the appropriate node start from the head, keep moving until you reach a node X who’s value is greater than the input node. The node just before X is the appropriate node .
- Insert the node after the appropriate node found in step 3.
refer to the code (commented) :- https://ide.codingblocks.com/s/234607
1 Like
Got it. Thanks for your help.