-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
82 lines (67 loc) · 1.54 KB
/
MergeSort.java
File metadata and controls
82 lines (67 loc) · 1.54 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
package exercise;
public class MergeSort {
public static void main(String[] args) {
Node head = new Node(5);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(7);
loop(head);
head = mergeSort(head);
loop(head);
}
public static void loop(Node head){
while (head!=null){
System.out.print(head.data+"->");
head=head.next;
}
System.out.println();
}
public static Node mergeSort(Node head){
if(head==null || head.next==null)
return head;
Node middle = findMiddle(head);
System.out.println(middle.data);
Node right = mergeSort(middle.next);
middle.next = null;
Node left = mergeSort(head);
Node sort = sorted(left,right);
return sort;
}
private static Node sorted(Node left, Node right){
Node result = null;
if(left ==null)
return right;
if(right == null)
return left;
if(left.data<right.data){
result =left;
result.next= sorted(left.next,right);
}
else {
result =right;
result.next= sorted(left,right.next);
}
return result;
}
private static Node findMiddle(Node head){
if(head==null)
return head;
Node slw=head, fst= head.next;
while (fst!=null){
fst=fst.next;
while (fst!=null){
fst=fst.next;
slw=slw.next;
}
}
return slw;
}
static class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
}
}
}