-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmsslrc.java
More file actions
130 lines (123 loc) · 3.58 KB
/
Copy pathmsslrc.java
File metadata and controls
130 lines (123 loc) · 3.58 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// msslrc.java - merge sort single link list recursive
package x;
import java.util.Random;
class Node{
Node next;
int data;
Node(){
data = 0;
}
Node(int d){
data = d;
}
}
class NodePair{
Node first;
Node last;
}
public class x {
static void merge(Node prev, Node f0, int n0,
Node f1, int n1, NodePair np)
{
Node first = f0.data <= f1.data ? f0 : f1;
Node last = prev;
int i = 0;
int j = 0;
while(true){
if(f0.data <= f1.data){ // if f0 < f1
last.next = f0; // move f0
last = f0;
f0 = f0.next;
if(++i < n0) // if not end run 0
continue; // continue back to while
last.next = f1; // else link run 1
while(++j < n1)
f1 = f1.next;
last = f1;
f1 = f1.next;
break;
} else {
last.next = f1; // move f1
last = f1;
f1 = f1.next;
if(++j < n1) // if not end run 1
continue; // continue back to while
last.next = f0; // else link run 0
while(++i < n0)
f0 = f0.next;
last = f0;
// f0 = f0.next;
break;
}
}
np.first = first;
np.last = last;
last.next = f1;
}
static void mergesort(Node prev, Node f0, int n0, NodePair np)
{
if(n0 <= 1){
np.first = np.last = f0;
return;
}
Node f1;
int n1;
n1 = n0; n0 >>= 1; n1 -= n0;
mergesort(prev, f0, n0, np);
f0 = np.first;
f1 = np.last.next;
mergesort(np.last, f1, n1, np);
f1 = np.first;
merge(prev, f0, n0, f1, n1, np);
}
// test sort
static Node testsort(Node head, int n)
{
Node node = head;
NodePair np= new NodePair();
Node prev = new Node();
prev.next = head;
long bgn, end;
int i;
// fill list with random data
Random r = new Random();
for(i = 0; i < n; i++){
node.data = r.nextInt();
node = node.next;
}
// time sort
bgn = System.currentTimeMillis();
mergesort(prev, head, n, np);
end = System.currentTimeMillis();
System.out.println("milliseconds " + (end-bgn));
// verify sort
i = 1;
node = prev.next;
while(node.next != null){
if(node.data > node.next.data)
break;
node = node.next;
i++;
}
if(i == n)
System.out.println("sort passed");
else
System.out.println("sort failed");
return prev.next;
}
// main
public static void main(String[] args) {
// create list
final int COUNT = 16*1024*1024;
Node head, node;
int i;
head = new Node();
node = head;
for(i = 1; i < COUNT; i++){
node.next = new Node();
node = node.next;
}
head = testsort(head, COUNT); // test sort with sequential nodes
testsort(head, COUNT); // test sort with scattered nodes
}
}