148. Sort List**

来源:互联网 发布:php断点续传原理 编辑:程序博客网 时间:2024/06/05 07:00

Sort a linked list in O(n log n) time using constant space complexity.

public class Solution {    public ListNode sortList(ListNode head) {        if(head ==null ||head.next==null) return head;        ListNode prev = null, slow = head, fast = head;        while(fast!=null&&fast.next!=null){            prev = slow;            slow = slow.next;            fast = fast.next.next;        }        prev.next = null;        ListNode l1 = sortList(head);        ListNode l2 = sortList(slow);        return merge(l1,l2);    }    public ListNode merge(ListNode l1,ListNode l2){        ListNode l = new ListNode(0), p=l;        while(l1!=null&&l2!=null){            if(l1.val<l2.val){                p.next = l1;                l1= l1.next;            }            else{                p.next = l2;                l2=l2.next;            }            p=p.next;        }        if(l1!=null) p.next = l1;        if(l2!=null) p.next = l2;        return l.next;            }}

总结:归并排序

排序法

最差时间分析平均时间复杂度稳定度空间复杂度冒泡排序O(n2)O(n2)稳定O(1)快速排序O(n2)O(n*log2n)不稳定O(log2n)~O(n)选择排序O(n2)O(n2)稳定O(1)二叉树排序O(n2)O(n*log2n)不一顶O(n)

插入排序

O(n2)O(n2)稳定O(1)堆排序O(n*log2n)O(n*log2n)不稳定O(1)希尔排序OO不稳定O(1)表格转载自:http://blog.csdn.net/wuxinyicomeon/article/details/5996675/

0 0