Java -- Parallel Array Algorithms

"Arrays.parallelSort" method can sort an array. For example,

String contents = new String(Files.readAllBytes(Path.get("alice.txt")), StandardCharsets.UTF_8);
String[] words = contents.split("[\\P{L}]+");
Arrays.parallelSort(words);

When you sort objects, you can supply a "Comparator".

Arrays.parallelSort(words, Comparator.comparing(String::length));

With all methods, you can supply the bounds of a range, such as

value.parallelSort(values.length()/2, values.length());

The "parallelSetAll" method fills an array with values that are computed from a function. The function receives the element index and computes the value at that position.

Arrays.parallelSetAll(values, i -> i % 10);  // Fills values with 0 1 2 3 ...

Finnaly, there is a "parallelPrefix" method that replaces each array element with the accumulation of the prefix for a given associative operation. Here is an example. Consider the array [1, 2, 3, ...] and the "*" operation. After executing 

Arrays.parallelPrefix(values, (x, y) -> x * y);

the array contains 

[1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, ...]

Perhaps suprisingly, this computation can be parallelized. First, join neighboring elements, , as indicated here:

[1, 1 * 2, 3, 3 * 4, 5, 5 * 6, 7, 7 * 8]

The gray value are left alone. Clearly, one can make this computation in parrallel in separate regions of the array. In the next step, update the indicated elements by multiplying them with elements that are one or two position below:

[1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, 5, 5 * 6, 5 * 6 * 7, 5 * 6 * 7 * 8]
This can again be done in parallel. After log(n) steps, the process is complete. This is a win over the straightforward linear computation if sufficient processors are available. On special-purpose hardware, this algorithm is commonly used, and users of such hardware are quite ingenious in adapting it to a variety of problems.

猜你喜欢

转载自blog.csdn.net/liangking81/article/details/80828401