Boudewijn said:
"Wannabee" <
[email protected]> schreef in bericht
"Sharp"
Hi
I have an array of integers.
I would like to retrieve the maximum integer from that array.
Have you considered using
static void java.util.Arrays.sort (int[] a)
Overkill.
And woefully inefficient on modern hardware, too.
To take advantage of SMP systems, CMT processors, even
hyperthreaded(tm) machines, you need some parallelism.
Here's the approach I'd recommend:
- If there are N numbers in the array, launch N/2
threads and give each thread two of the numbers.
Each thread's job is to compute the larger of the
two numbers it's been given. (If N is odd, launch
one extra thread to compute the larger of the final
value and Integer.MIN_VALUE.)
- When all N/2 threads have terminated, collect the
N/2 "first round winners" that they computed. You
have reduced the problem size by half, the first
step of a classic divide-and-conquer strategy.
- Now launch N/4 threads, handing each of them a pair
of the "first round winners." Collect their N/4
results and launch N/8 threads to compute the winners
of the next round, and so on until you finish up by
running N/N == 1 thread to compute the larger of the
two "semifinalists:" the Grand Champion.
This requires only ceil(lg(N)) stages, with each stage
except the final few exploiting all the computing resources
on the system toward the solution of the problem. That's
why it's so much more efficient than the primitive single-
threaded O(N) methods suggested thus far, methods that
cannot hope to take advantage of today's machines.
;-)