链表排序之快速排序

Posted earthhouge

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表排序之快速排序相关的知识,希望对你有一定的参考价值。

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

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

以上是关于链表排序之快速排序的主要内容,如果未能解决你的问题,请参考以下文章

常用排序算法之冒泡排序选择排序

链表的快速排序问题

算法排序之堆排序

C快速排序(链表)分段错误

常见的链表排序(Java版)

链表的快速排序和归并排序