147. Insertion Sort List

Source: Internet
Author: User

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:

    1. Starting with the first element, the element can be thought to have been sorted
    2. Takes the next element and scans the sequence of elements that have been sorted from back to forward
    3. If the element (sorted) is greater than the new element, move the element to the next position
    4. Repeat step 3 until you find the sorted element is less than or equal to the position of the new element
    5. After inserting a new element into the position
    6. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.