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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值