Intuition & Algorithm
The diagram and illustration in the question have given us a clear description of insertion sort algorithm.
- Separate the list into two parts:
sortedandsorting - Insert the head of
sortinglist into the sorted list
We should consider three cases during insertion(v is the node to be inserted):
v < sorted.head.valwe should use this node as the new head of sorted listcur.val < v < cur.next.valcuris a node in the sorted list, in this case we should insert the new node betweencurandcur.nextcur.next == nullthis meansvis large than any number in the list, so we append it to the tail.
Code
1 | /** |
Complexity
Time Complexity: $O(n)$
Spatial Complexity: $O(1)$