-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Sort_Linkedlist.java
More file actions
83 lines (62 loc) · 1.77 KB
/
Merge_Sort_Linkedlist.java
File metadata and controls
83 lines (62 loc) · 1.77 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
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
/*
Given Pointer/Reference to the head of the linked list, the task is to Sort the given linked list using Merge Sort.
Note: If the length of linked list is odd, then the extra node should go in the first list while splitting.
N = 5
value[] = {3,5,2,4,1}
Output: 1 2 3 4 5
*/
class LinkedList
{
public static Node merge(Node left, Node right){
if(left==null){
return right;
}
if(right==null){
return left;
}
Node res = null;
if(left.data<=right.data){
res = left;
res.next = merge(left.next, right);
}else{
res = right;
res.next = merge(left,right.next);
}
return res;
}
// function to get the middle of the linked list
public static Node getMiddle(Node head)
{
if (head == null)
return head;
Node slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
static Node mergeSort(Node head)
{
// add your code here
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);
Node headAfterSort = merge(left,right);
return headAfterSort;
/*
3 5 2 4 1
*/
/*
3->5
left = mergeSort(3,5)
left = mergeSort(3,2)
mergeSort(3,1)
*/
}
}