Of course, Diveide-and-conquer computation of the array's sum is possible. But I cannot see a UseCase for it? You're still computing at least the same amount of sums, you're still running into issues if the sum of array
is greater than Integer.MAX_VALUE
, ...
There is also no performance benefit like Codor showed in his answer to a related question.
Starting with Java 8 you can compute the sum in 1 line using streams.
int sum = Arrays.stream(array).sum();
The main flaw with your above code is the fact that you're only summing up index mid
(2) and end
(4). After that you skip to the lower bracket (index mid = 0
and end = 2
). So you're missing index 3. This problem will become even more prevelant with larger arrays because you're skipping even more indices after the while
's first iteration.
A quick Google search brought up this nice-looking talk about the general Divide-and-Conquer principle using a mechanism called Recursion. Maybe it can guide you to a working solution.