Given an array of integers, find the index of the first positive element in the array. For example, if the array contains the following five elements: -3, -1, 4, -5, 6. The first positive element is 4. Thus, the index is 2. This is a very simple problem and can be solved as follows:
At the end, if variable posIndex is negative, all elements in array a[] are negative; otherwise, the value of posIndex is the desired index.posIndex = -1; for (i = 0; i < n; i++) if (a[i] > 0) { posIndex = i; break; }
How can we solve this problem using multiple threads? In fact, a possible solution is very similar to the maximum finding problem. For any two different elements of the input array, say a[i] and a[j], where i < j, we have the following four cases to consider:
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Value | -1 | -3 | 5 | -2 | 6 | -7 | -8 | 4 | 5 |
The following shows how the cross-out procedure proceeds:
i | a[i] | j | a[j] | Case | Result |
0 | -1 | 1 | -3 | case (2) | cross out both |
2 | 5 | case (4) | cross out a[0] | ||
3 | -2 | case (2) | cross out both | ||
4 | 6 | case (4) | cross out a[0] | ||
5 | -7 | case (2) | cross out both | ||
6 | -8 | case (2) | cross out both | ||
7 | 4 | case (4) | cross out a[0] | ||
8 | 5 | case (4) | cross out a[0] | ||
1 | -3 | 2 | 5 | case (4) | cross out a[1] |
3 | -2 | case (2) | cross out both | ||
4 | 6 | case (4) | cross out a[1] | ||
5 | -7 | case (2) | cross out both | ||
6 | -8 | case (2) | cross out both | ||
7 | 4 | case (4) | cross out a[1] | ||
8 | 5 | case (4) | cross out a[1] | ||
2 | 5 | 3 | -2 | case (3) | cross out a[3] |
4 | 6 | case (1) | cross out a[4] | ||
5 | -7 | case (3) | cross out a[5] | ||
6 | -8 | case (3) | cross out a[6] | ||
7 | 4 | case (1) | cross out a[7] | ||
8 | 5 | case (1) | cross out a[8] | ||
3 | -2 | 4 | 6 | case (4) | cross out a[3] |
5 | -7 | case (2) | cross out both | ||
6 | -8 | case (2) | cross out both | ||
7 | 4 | case (4) | cross out a[3] | ||
8 | 5 | case (4) | cross out a[3] | ||
4 | 6 | 5 | -7 | case (3) | cross out a[5] |
6 | -8 | case (3) | cross out a[6] | ||
7 | 4 | case (1) | cross out a[7] | ||
8 | 5 | case (1) | cross out a[8] | ||
5 | -7 | 6 | -8 | case (2) | cross out both |
7 | 4 | case (4) | cross out a[5] | ||
8 | 5 | case (4) | cross out a[5] | ||
6 | -8 | 7 | 4 | case (4) | cross out a[6] |
8 | 5 | case (4) | cross out a[6] | ||
7 | 4 | 8 | 5 | case (1) | cross out a[8] |
From the above, we learn that a[2] is never crossed out, and, hence the index is 2! That is, a[2] is the first positive element of array a[ ].
The following summarizes this cross-out algorithm:
Write a program that reads in an array of some integers and use the above algorithm to find its first positive element. Will you be able to simplify the above cases? Note that you should aim for maximum parallelism. More precisely, all created threads should run concurrently.