-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQuickSortLinkedList.java
More file actions
52 lines (47 loc) · 2.21 KB
/
QuickSortLinkedList.java
File metadata and controls
52 lines (47 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import util.ListNode;
public class QuickSortLinkedList {
private ListNode tail;
public ListNode quickSort(ListNode head) { // TC: average O(nlogn), worst O(n^2), SC: O(log(n))
if (head == null) return null;
if (head.next == null) return tail = head;
ListNode small = new ListNode(0); // will use small as dummy head of all result
ListNode large = new ListNode(0);
partition(head, small, large); // use head as pivot
head.next = null; // must cut it
if (small.next != null) {
small.next = quickSort(small.next);
tail.next = head;
} else small.next = head;
tail = head;
tail.next = quickSort(large.next);
return small.next;
}
private void partition(ListNode head, ListNode small, ListNode large) { // Notice small & large, java pass by value
ListNode cur = head.next;
while (cur != null) {
if (cur.value < head.value) {
small.next = cur;
small = small.next;
} else {
large.next = cur;
large = large.next;
}
cur = cur.next;
}
small.next = large.next = null;
}
public static void main(String[] args) {
QuickSortLinkedList qs = new QuickSortLinkedList();
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{9, 7, 0, 5, 4, 1, 8, 2, 6, 3})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{5, 4, 1, 2, 6, 3})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{4, 2, 6, 3, 5})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{8, 5, 3, 1})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{1, -1, 0})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{8, 5, 3})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{2, 8})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{8, 2})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{3})));
System.out.println(qs.quickSort(ListNode.fromArray(new int[]{0})));
System.out.println(qs.quickSort(ListNode.fromArray(null)));
}
}