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:
sorted
andsorting
- Insert the head of
sorting
list into the sorted list
We should consider three cases during insertion(v is the node to be inserted):
v < sorted.head.val
we should use this node as the new head of sorted listcur.val < v < cur.next.val
cur
is a node in the sorted list, in this case we should insert the new node betweencur
andcur.next
cur.next == null
this meansv
is 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)$