标签:
1. 归并排序
归并排序是基于一种被称为“分治”(divide and conquer)的策略。
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
method 1: merge sort, 用divide and conquer的方式,先把list分为左右部分,然后排序后合并
2. 快速排序
伪代码:
function quicksort(q) var list less, pivotList, greater if length(q) ≤ 1 { return q } else { select a pivot value pivot from q for each x in q except the pivot element if x < pivot then add x to less if x ≥ pivot then add x to greater add pivot to pivotList return concatenate(quicksort(less), pivotList, quicksort(greater)) }
Linkedlist quick sort
public class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode mid = findMedian(head); // O(n) //new three dummmy node with a tail point to it ListNode leftDummy = new ListNode(0), leftTail = leftDummy; ListNode rightDummy = new ListNode(0), rightTail = rightDummy; ListNode middleDummy = new ListNode(0), middleTail = middleDummy; //sprate to three part while (head != null) { if (head.val < mid.val) { leftTail.next = head; leftTail = head; } else if (head.val > mid.val) { rightTail.next = head; rightTail = head; } else { middleTail.next = head; middleTail = head; } head = head.next; } //make the tail to null leftTail.next = null; middleTail.next = null; rightTail.next = null; //recurisive do the sort ListNode left = sortList(leftDummy.next); ListNode right = sortList(rightDummy.next); //connect the three parts together return concat(left, middleDummy.next, right); } private static ListNode findMedian(ListNode head) { ListNode fast = head.next; ListNode slow = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } private static ListNode concat(ListNode left, ListNode mid, ListNode right) { ListNode dummy = new ListNode(0), dummyTail = dummy; dummyTail = connect(dummyTail, left); dummyTail = connect(dummyTail, mid); dummyTail = connect(dummyTail, right); return dummy.next; } private static ListNode connect(ListNode dummyTail, ListNode current) { while (current != null) { dummyTail.next = current; dummyTail = dummyTail.next; current = current.next; } return dummyTail; } }
标签:
原文地址:http://www.cnblogs.com/jiangchen/p/5935343.html