链表排序之快速排序
链表排序之插入快速算法:
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
相关推荐
earthhouge 2020-08-15
dbhllnr 2020-06-04
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
aanndd 2020-08-12
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18
bluetears 2020-07-05
fengshantao 2020-07-02
liuweixiao0 2020-06-27