147. Insertion Sort List
Last updated
Last updated
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
Example 1:
Example 2:
看似简单的链表插入排序,但是实现起来确实需要注意很多细节问题。提一个代码中最重要的点就是,尾指针下一个如果比他大,就不需要插入,这时候尾指针需要后移一位。但是如果比他小,就不需要移动,因为下一位插入到前面去了,新的下一位就接在尾指针后面
插入排序时间复杂度是O(n²),两个循环,每个执行n次,循环中操作是O(1)的。