Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8420940

Browse files
author
Ram swaroop
committed
quick sort for linked list: done
1 parent f29a337 commit 8420940

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package me.ramswaroop.linkedlists;
2+
3+
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 7/21/15
11+
* @time: 11:43 PM
12+
*/
13+
public class QuickSort {
14+
15+
public static <E extends Comparable<E>> SingleLinkedNode<E>[] partition(SingleLinkedNode<E> firstNode,
16+
SingleLinkedNode<E> lastNode) {
17+
18+
SingleLinkedNode<E>[] partition = new SingleLinkedNode[4];
19+
SingleLinkedNode<E> pivot = lastNode, curr = new SingleLinkedNode<>(null, firstNode), currNext, pivotNext;
20+
21+
while (curr.next != null && curr.next != lastNode) {
22+
if (curr.next.item.compareTo(pivot.item) > 0) {
23+
currNext = curr.next;
24+
curr.next = currNext.next;
25+
pivotNext = pivot.next;
26+
pivot.next = currNext;
27+
currNext.next = pivotNext;
28+
continue;
29+
}
30+
curr = curr.next;
31+
}
32+
33+
partition[0] = curr;
34+
35+
while (curr.next != pivot) {
36+
curr = curr.next;
37+
}
38+
partition[1] = curr;
39+
40+
partition[2] = pivot.next;
41+
42+
while (curr.next != null) {
43+
curr = curr.next;
44+
}
45+
partition[3] = curr;
46+
47+
return partition;
48+
49+
}
50+
51+
public static <E extends Comparable<E>> SingleLinkedNode<E> quickSort(SingleLinkedNode<E> firstNode,
52+
SingleLinkedNode<E> lastNode) {
53+
54+
SingleLinkedNode<E> head = firstNode;
55+
if (firstNode != lastNode) {
56+
SingleLinkedNode<E> partition[] = partition(firstNode, lastNode);
57+
head = quickSort(partition[0], partition[1]);
58+
quickSort(partition[2], partition[3]);
59+
}
60+
61+
return head;
62+
}
63+
64+
public static <E extends Comparable<E>> SingleLinkedNode<E> quickSort(SingleLinkedNode<E> node) {
65+
return quickSort(node, getLastNode(node));
66+
}
67+
68+
public static <E extends Comparable<E>> SingleLinkedNode<E> getLastNode(SingleLinkedNode<E> node) {
69+
SingleLinkedNode<E> curr = node;
70+
71+
while (curr != null && curr.next != null) {
72+
curr = curr.next;
73+
}
74+
75+
return curr;
76+
}
77+
78+
public static void main(String a[]) {
79+
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
80+
linkedList.add(23);
81+
linkedList.add(4);
82+
linkedList.add(45);
83+
linkedList.add(11);
84+
linkedList.add(7);
85+
linkedList.printList();
86+
linkedList.printList(quickSort(linkedList.head));
87+
}
88+
}

0 commit comments

Comments
 (0)