Skip to content

Commit 5299e3b

Browse files
committed
commit Exercise_30_13
1 parent cf4c1f3 commit 5299e3b

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package exercise_30_13;
2+
3+
import static exercise_23_02.Exercise_23_02.merge;
4+
import static exercise_23_02.Exercise_23_02.mergeSort;
5+
import java.util.Arrays;
6+
import java.util.concurrent.ForkJoinPool;
7+
import java.util.concurrent.RecursiveAction;
8+
9+
public class Exercise_30_13 {
10+
11+
public static void main(String[] args) {
12+
final int SIZE = 7000000;
13+
Integer[] list1 = new Integer[SIZE];
14+
Integer[] list2 = new Integer[SIZE];
15+
16+
for (int i = 0; i < list1.length; i++)
17+
list1[i] = list2[i] = new Integer((int)(Math.random() * 10000000));
18+
19+
long startTime = System.currentTimeMillis();
20+
parallelMergeSort(list1);
21+
long endTime = System.currentTimeMillis();
22+
System.out.println("\nParallel time with " + Runtime.getRuntime().availableProcessors() +
23+
" processors is " + (endTime - startTime) + " milliseconds");
24+
25+
startTime = System.currentTimeMillis();
26+
mergeSort(list2);
27+
endTime = System.currentTimeMillis();
28+
System.out.println("\nSequential time is " + (endTime - startTime) + " milliseconds");
29+
}
30+
31+
public static <E extends Comparable<E>> void parallelMergeSort(E[] list) {
32+
RecursiveAction mainTask = new SortTask(list);
33+
ForkJoinPool pool = new ForkJoinPool();
34+
pool.invoke(mainTask);
35+
}
36+
37+
private static class SortTask<E extends Comparable<E>> extends RecursiveAction {
38+
private final int THRESHOLD = 500;
39+
private E[] list;
40+
41+
SortTask(E[] list) {
42+
this.list = list;
43+
}
44+
45+
@Override
46+
protected void compute() {
47+
if(list.length < THRESHOLD) {
48+
Arrays.sort(list);
49+
}
50+
else {
51+
E[] firstHalf = (E[])(new Comparable[list.length / 2]);
52+
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
53+
54+
int secondHalfLength = list.length - list.length / 2;
55+
E[] secondHalf = (E[])(new Comparable[secondHalfLength]);
56+
System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
57+
58+
invokeAll(new SortTask(firstHalf), new SortTask(secondHalf));
59+
60+
merge(firstHalf, secondHalf, list);
61+
}
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)