-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
81 lines (61 loc) · 1.39 KB
/
Copy pathMergeSort.java
File metadata and controls
81 lines (61 loc) · 1.39 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
import java.util.Arrays;
public class MergeSort<AnyType extends Comparable<? super AnyType>> extends Thread
{
private AnyType[] v;
public MergeSort(AnyType[] items)
{
v = Arrays.copyOfRange(items, 0, items.length);
}
public void getSortedValues(AnyType[] items)
{
for (int i = 0; i < items.length; i++)
items[i] = v[i];
}
public void run()
{
int mid;
AnyType[] v1, v2;
if (v.length <= 1)
return;
mid = ( v.length / 2);
v1 = Arrays.copyOfRange(v, 0, mid);
v2 = Arrays.copyOfRange(v, mid, v.length);
MergeSort<AnyType> thrd1 = new MergeSort<AnyType>(v1);
MergeSort<AnyType> thrd2 = new MergeSort<AnyType>(v2);
thrd1.start();
thrd2.start();
try {
thrd1.join();
thrd2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
merge(thrd1.v, thrd2.v);
}
private void merge(AnyType[] v1, AnyType[] v2)
{
int i, j, n1, n2;
i = 0;
j = 0;
n1 = v1.length;
n2 = v2.length;
int r = 0;
while( i < n1 && j < n2 )
{
if( v1[i].compareTo(v2[j]) < 0 )
v[r++] = v1[i++];
else if( v2[j].compareTo(v1[i]) < 0 )
v[r++] = v2[j++];
else
v[r++] = v1[i++];
}
while( i < n1)
{
v[r++] = v1[i++];
}
while( j < n2)
{
v[r++] = v2[j++];
}
}
}