-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathMergeSortLinkedList.java
101 lines (81 loc) · 2.14 KB
/
MergeSortLinkedList.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class MergeSortLinkedList {
Node head;
public Node mergeSort(Node head) {
if (head == null || head.next == null) {
return head;
}
Node middle = getMiddle(head);
Node nextOfMiddle = middle.next;
middle.next = null;
Node left = mergeSort(head);
Node right = mergeSort(nextOfMiddle);
return merge(left, right);
}
public Node getMiddle(Node head) {
if (head == null) {
return head;
}
Node slow = head;
Node fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public Node merge(Node a, Node b) {
Node result = null;
if (a == null) {
return b;
}
if (b == null) {
return a;
}
if (a.data <= b.data) {
result = a;
result.next = merge(a.next, b);
} else {
result = b;
result.next = merge(a, b.next);
}
return result;
}
public void addNode(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
public void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
MergeSortLinkedList list = new MergeSortLinkedList();
list.addNode(12);
list.addNode(8);
list.addNode(10);
list.addNode(5);
list.addNode(1);
list.addNode(6);
System.out.println("Linked List before sorting:");
list.printList(list.head);
list.head = list.mergeSort(list.head);
System.out.println("Linked List after sorting:");
list.printList(list.head);
}
}