derp
derp

Reputation: 411

Meximum Subarray Sum using Divide-And-Conquer

Working on an implementation of finding the Greatest Contiguous Sum of a sequence using the Divide and Conquer method as seen here.

My return value is often incorrect. For example:

{5, 3} returns 5 instead of 8.
{-5, 3} returns 0 instead of 3.
{ 6, -5, 7 } returns 7 instead of 8. 

Other notes:

Upvotes: 0

Views: 245

Answers (1)

The Dark
The Dark

Reputation: 8514

You have two problems with your code:

A. This loop:

for (RAIter i = center; i > first; i--)

does not include first in the loop. The reference algorithm does. You can't just use >= as the reference algorithm does as it doesn't work for iterators. Either add an extra bit of code to check first at the end, or change your loop so it somehow includes first (maybe a do while loop would suit better).

B. These definitions:

size_t sum = 0;
size_t leftSum = 0;
size_t rightSum = 0;

should not be size_t as size_t is unsigned. This means that when the sum goes negative, checks like if(sum > leftSum) no longer work, as the negative value (which underflows) is bigger than the positive value.

Change them to int.

The best way to find these kinds of errors is to run the code through a debugger. You can then step through each line of your code and see what the variable values are. This makes it easy to spot things like negative numbers becoming large positive numbers as above.

Upvotes: 1

Related Questions