Sort a linked list using insertion sort.
Complexity O (n^2);
Insert Sort (insertion sort)
There is a set of keywords {K1, K2, ..., Kn}; the sort begins with the thought that K1 is an ordered sequence; let K2 insert an ordered sequence with a table length of 1 so that it becomes an ordered sequence with a table length of 2, and then let K3 insert an ordered sequence with a table length of 2, making it an ordered sequence of 3; The second analogy, and finally let the Kn insert the above table length as n-1 ordered sequence, a table length of n ordered sequence.
The specific algorithm is described as follows:
- Starting with the first element, the element can be thought to have been sorted
- Takes the next element and scans the sequence of elements that have been sorted from back to forward
- If the element (sorted) is greater than the new element, move the element to the next position
- Repeat step 3 until you find the sorted element is less than or equal to the position of the new element
- After inserting a new element into the position
- Repeat step 2~5
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode insertionsortlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL) returnHead; ListNode Dummy=NewListNode (0); ListNode Pre=dummy; ListNode cur=Head; while(cur! =NULL) {ListNode next=Cur.next; while(Pre.next! =NULL&& Pre.next.val <cur.val) {Pre=Pre.next; } //Insert cur nodein pre and pre.next;Cur.next =Pre.next; Pre.next=cur; Pre=dummy; Cur=Next; } returnDummy.next; }}
147. Insertion Sort List