forked from slgobinath/Java-Helps-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchArray.java
More file actions
66 lines (59 loc) · 1.84 KB
/
SearchArray.java
File metadata and controls
66 lines (59 loc) · 1.84 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
import java.util.Random;
import java.util.concurrent.*;
/**
* Count the number of occurences of a number in an array using Fork/Join framework.
*
* @author L.Gobinath
*/
public class SearchArray {
public static void main(String[] args) {
int[] array = {5, 6, 3, 2, 8, 1, 5, 5, 3, 9, 7, 5, 2, 4};
// Search for 5
Counter counter = new Counter(5, array, 0, array.length - 1);
// Create a pool of threads
ForkJoinPool pool = new ForkJoinPool();
// Start execution and wait for result
int count = pool.invoke(counter);
System.out.println("Count: " + count); // Count: 4
}
}
class Counter extends RecursiveTask<Integer> {
// The number to search
private int num;
private int[] array;
private int left;
private int right;
public Counter(int num, int[] array, int left, int right) {
this.num = num;
this.array = array;
this.left = left;
this.right = right;
}
/**
* Inherited from RecursiveAction.
* Compare it with the run method of a Thread.
*/
@Override
public Integer compute() {
if (left == right) {
// Check the number
if (array[left] == num) {
return 1;
}
} else if (left < right) {
int mid = (left + right) / 2;
// Create sub tasks
RecursiveTask<Integer> leftTask = new Counter(num, array, left, mid);
RecursiveTask<Integer> rightTask = new Counter(num, array, mid + 1, right);
// Execute the sub tasks
leftTask.fork();
rightTask.fork();
int count = 0;
// Wait and recieve the outputs from sub tasks
count += leftTask.join();
count += rightTask.join();
return count;
}
return 0;
}
}