![]() |
VOOZH | about |
Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm.
Examples:
Input: 5->4->1->3->2
Output: 1->2->3->4->5
Input: 4->3->2->1
Output: 1->2->3->4
The prerequisite is Insertion Sort on Array. The idea is to gradually build a sorted portion of the list within the same memory space as the original list.
Step-by-step approach:
Below is the implementation of the above approach
1 2 3 4 5
Time Complexity: O(n2), In the worst case, we might have to traverse all nodes of the sorted list for inserting a node.
Auxiliary Space: O(1), No extra space is required