码迷,mamicode.com
首页 > 其他好文 > 详细

problem report: sort list

时间:2016-05-28 06:38:10      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

quick sort version 1: 

  quick sort 定义: https://en.wikipedia.org/wiki/Quicksort

  quick sort 核心部分为partition(http://www.cnblogs.com/jiangchen/p/5398166.html),

            取list中间点(http://www.cnblogs.com/jiangchen/p/5529704.html)

  时间复杂度为o(nlgn)  

技术分享
 1 public class Solution {
 2     //recursive partition list to left,middle,right 3 parts, use concat function to conntet 3 parts together at end of function 
 3     public ListNode sortList(ListNode head) {  
 4         if (head == null || head.next == null) {
 5             return head;
 6         }
 7         ListNode middle = findMedian(head);
 8         
 9         ListNode leftDummy = new ListNode(0), leftTail = leftDummy;
10         ListNode rightDummy = new ListNode(0), rightTail = rightDummy;
11         ListNode middleDummy = new ListNode(0), middleTail = middleDummy;
12         
13         while (head != null) {
14             if (head.val < middle.val) {
15                 leftTail.next = head;
16                 leftTail = head;
17             } else if(head.val == middle.val) {
18                 middleTail.next = head;
19                 middleTail = head;
20             } else {
21                 rightTail.next = head;
22                 rightTail = head;
23             }
24             head = head.next;
25         }
26         leftTail.next = null;
27         middleTail.next = null;
28         rightTail.next = null;
29         
30         ListNode left = sortList(leftDummy.next);
31         ListNode right = sortList(rightDummy.next);
32         
33         return concat(left, middleDummy.next, right);
34     }
35     // connect 3 part together
36     private ListNode concat (ListNode left, ListNode mid, ListNode right) {
37         ListNode dummy = new ListNode(0), tail = dummy;
38         tail.next = left;
39         tail = getTail(tail);//left 本身可能是一个空串,所以3次getTail都用tail作为起始点,而不用left,mid,right
40         tail.next = mid;
41         tail = getTail(tail);
42         tail.next = right;
43         tail = getTail(tail);
44         return dummy.next;
45     }
46     //get end of current list 
47     private ListNode getTail (ListNode current) {
48         if (current == null) {
49             return current;
50         }
51         while (current.next != null) {
52             current = current.next;
53         }
54         return current;
55     }
56     
57     private ListNode findMedian(ListNode head) {
58         ListNode slow = head, fast = head.next;
59         while (fast != null && fast.next != null) {
60             slow = slow.next;
61             fast = fast.next.next;
62         }
63         return slow;
64     }
65 }
View Code

 

              

problem report: sort list

标签:

原文地址:http://www.cnblogs.com/jiangchen/p/5536689.html

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