码迷,mamicode.com
首页 > 编程语言 > 详细

链表排序之快速排序

时间:2019-10-28 21:15:36      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:span   算法   partition   链表   sort   stat   rtl   null   void   

链表排序之插入快速算法:

public static ListNode quickSortList(ListNode head){
        if (null == head || null == head.next){
            return head;
        }
        ListNode preHead = new ListNode(-1);
        quickSortList(preHead, head, null);
        return preHead.next;
    }
    private static void quickSortList(ListNode preHead, ListNode head, ListNode tail){
        if (head != tail && head.next != tail){
            ListNode mid = partition(preHead, head, tail);
            quickSortList(preHead, preHead.next, mid);
            quickSortList(mid, mid.next, tail);
        }
    }
    private static ListNode partition(ListNode lowPre, ListNode low, ListNode high){
        int key = low.val;
        ListNode head1 = new ListNode(-1);
        ListNode head2 = new ListNode(-1);
        ListNode l = head1;
        ListNode h = head2;
        for (ListNode node = low.next; node != high; node = node.next){
            if (node.val <= key){
                l.next = node;
                l = node;
            }else {
                h.next = node;
                h = node;
            }
        }
        h.next = high;
        l.next = low;
        low.next = head2.next;
        lowPre.next = head1.next;
        return low;
    }

排序前:6 2 8 4 9 5 1 3 7

排序后:1 2 3 4 5 6 7 8 9

链表排序之快速排序

标签:span   算法   partition   链表   sort   stat   rtl   null   void   

原文地址:https://www.cnblogs.com/earthhouge/p/11754613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!