简体   繁体   中英

Divide And Conquer Sum Of Array Of Integers

I wrote the below program to find the sum of all integers using divide and conquer recursion algorithm in Java:

But somehow the sum is coming incorrectly.

public class DivideAndConquerSum {
 public static void main(String[] args) {
    int[] arr = new int[]{2, 3, 4, 5};
    System.out.println(calculateRecursiveSum(arr, 0, arr.length));
  }
  static long sum = 0;
  static long calculateRecursiveSum(int[] arr, int low, int high) {
    if (high == low) {
      return arr[0];
    } else {
      int mid = (high + low) / 2;
      sum = calculateRecursiveSum(arr, low, mid) +
            calculateRecursiveSum(arr, mid + 1, high);
    }
    return sum;
  }
}

Can anyone please let me know what is wrong in the code to resolve it? Assuming only positive integers in this scenario.

Your method basically recalculates mid so you need to return the value at that point. It is more suited to a binary search. But make the following changes and it will work.

       static long calculateRecursiveSum(int[] arr, int low, int high) {
          if (high == low) {
                return 0;
            }
            int mid = (high + low) / 2;
            return arr[mid] + calculateRecursiveSum(arr, low, mid) + 
                      calculateRecursiveSum(arr, mid+1, high);
       }

Your approach was almost okay, here I corrected few problems to keep your idea working.

public class DivideAndConquerSum
{
   public static void main(String[] args)
   {
      int[] arr = new int[] { 2, 3, 4, 5 };
      System.out.println(calculateRecursiveSum(arr, 0, arr.length - 1));
   }

   // static long sum = 0;
   static long calculateRecursiveSum(int[] arr, int low, int high)
   {
      // long sum=0;
      if (high == low)
      {
         return arr[low];
      }
      else
      {
         int mid = (high + low) / 2;
         return (calculateRecursiveSum(arr, low, mid) + calculateRecursiveSum(arr, mid + 1, high));
      }
      // return sum;
   }
}

You don't need an extra static variable to store the result. Returning the recursive call directly will do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM