-
Notifications
You must be signed in to change notification settings - Fork 0
/
SORTING OF LL USING MERGE SORT
79 lines (63 loc) · 1.72 KB
/
SORTING OF LL USING MERGE SORT
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
class Solution {
public:
ListNode* findMid(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head -> next;
while(fast != NULL && fast -> next != NULL) {
slow = slow -> next;
fast = fast -> next -> next;
}
return slow;
}
ListNode* merge(ListNode* left, ListNode* right) {
if(left == NULL)
return right;
if(right == NULL)
return left;
ListNode* ans = new ListNode(-1);
ListNode* temp = ans;
//merge 2 sorted Linked List
while(left != NULL && right != NULL) {
if(left -> val < right -> val) {
temp -> next = left;
temp = left;
left = left -> next;
}
else
{
temp -> next = right;
temp = right;
right = right -> next;
}
}
while(left != NULL) {
temp -> next = left;
temp = left;
left = left -> next;
}
while(right != NULL) {
temp -> next = right;
temp = right;
right = right -> next;
}
ans = ans -> next;
return ans;
}
ListNode* sortList(ListNode* head) {
//base case
if( head == NULL || head -> next == NULL ) {
return head;
}
// break linked list into 2 halvs, after finding mid
ListNode* mid = findMid(head);
ListNode* left = head;
ListNode* right = mid->next;
mid -> next = NULL;
//recursive calls to sort both halves
left = sortList(left);
right = sortList(right);
//merge both left and right halves
ListNode* result = merge(left, right);
return result;
}
};