-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMergeSort.java
74 lines (63 loc) · 1.8 KB
/
MergeSort.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
/*https://practice.geeksforgeeks.org/problems/sort-a-linked-list/1*/
class Solution
{
static Node merge(Node first, Node second)
{
Node newList = new Node(0);
Node curr = newList;
//normal merge process
while (first != null && second != null) {
if (first.data < second.data) {
curr.next = first;
first = first.next;
}
else {
curr.next = second;
second = second.next;
}
curr = curr.next;
}
// While first is not null
while (first != null) {
curr.next = first;
first = first.next;
curr = curr.next;
}
// While second is not null
while (second != null) {
curr.next = second;
second = second.next;
curr = curr.next;
}
return newList.next;
}
static Node getMid(Node head)
{
//two pointer approach
Node slow = head, fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
static Node mergeSort(Node head)
{
//if zero or one node, return
if (head == null || head.next == null)
return head;
//find the middle node
Node mid = getMid(head);
//find the break point
Node breakPoint = mid.next;
//divide into two separate lists
mid.next = null;
//recur on first list
Node first = mergeSort(head);
//recur on second list
Node second = mergeSort(breakPoint);
//merge
Node sortedList = merge(first, second);
return sortedList;
}
}