#include <iostream>

#include <numeric>

#include <iterator>

 

// an into two sub-arrays with the same

int partition(int arr[], int n)

{

    // calculate sum of all elements present in the array

    int total_sum = std::accumulate(arr, arr + n, 0);

 

    // variable to maintain sum of processed elements

    int sum_so_far = 0;

 

    // do for each element of the array

    for (int i = 0; i < n; i++)

    {

        // if sum of A[0..i-1] is equal to A[i, n-1]

        if (sum_so_far == total_sum sum_so_far)

            return i;

 

        // update sum_so_far by including value of the current element

        sum_so_far += arr[i];

    }

 

    return 1;

}

 

int main()

{

    int arr[] = { 6, 4, 3, 2, 3 };

    int n = sizeof(arr)/sizeof(arr[0]);

 

    // get index i that points to starting of second sub-array

    int i = partition(arr, n);

 

    if (i != 1)

    {

        // print the first sub-array [0, i-1]

        std::copy(arr, arr + i, std::ostream_iterator<int>(std::cout, ” “));

 

        std::cout << std::endl;

 

        // print the second sub-array [i, n-1]

        std::copy(arr + i, arr + n, std::ostream_iterator<int>(std::cout, ” “));

    }

    else {

        std::cout << “The array can’t be partitioned”;

    }

 

    return 0;

}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here