147. Insertion Sort List

來源:互聯網
上載者:User

標籤:位置   size   for   link   class   掃描   head   public   lis   

Sort a linked list using insertion sort. 

複雜度 o(n^2);

插入排序 (Insertion Sort)

設有一組關鍵字{K1, K2,…, Kn};排序開始就認為 K1 是一個有序序列;讓 K2 插入上述表長為 1 的有序序列,使之成為一個表長為 2 的有序序列;然後讓 K3 插入上述表長為 2 的有序序列,使之成為一個表長為 3 的有序序列;依次類推,最後讓 Kn 插入上述表長為 n-1 的有序序列,得一個表長為 n 的有序序列。

具體演算法描述如下:

  1. 從第一個元素開始,該元素可以認為已經被排序
  2. 取出下一個元素,在已經排序的元素序列中從後向前掃描
  3. 如果該元素(已排序)大於新元素,將該元素移到下一位置
  4. 重複步驟 3,直到找到已排序的元素小於或者等於新元素的位置
  5. 將新元素插入到該位置後
  6. 重複步驟 2~5
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode insertionSortList(ListNode head) {        if(head == null || head.next == null)            return head;        ListNode dummy = new ListNode(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;        }        return dummy.next;    }}

 

147. Insertion Sort List

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.