void display(int list[], int n)
{
int i;
for(i = 0 ; i < n; ++ i)
{
printf(" %d", list[i]);
}
printf("\n");
}
int find_diff(int num1, int num2)
{
if(num1 > num2)
return num1 - num2;
else
return num2 - num1;
}
void balance(int sum2, int sum1, int a2[], int a1[], int n)
{
int diff = (sum2 - sum1)/2;
int min, bal = 999999;
int idx1 , idx2, temp1, temp2;
int i = 0; int j = 0;
int FLAG = FALSE;
while(i < n && j < n)
{
min = a2[j] - a1[i];
if (min > 0)
{
if (min < diff * 2)
{
min = find_diff (min, diff);
if (bal > min)
{
bal = min;
idx1 = i;
idx2 = j;
i++;
FLAG = TRUE;
}
else
j++;
}
else
j++;
}
else
i++;
}
if (FLAG)
{
temp1 = a1[idx1];
temp2 = a2[idx2];
for (i = idx1; i >= 0; i--)
{
if(temp2 > a1[i - 1])
a1[i] = a1[i - 1];
else
{
a1[i] = temp2;
break;
}
}
for (i = idx2; i < n; i++)
{
if(temp1 < a2[i + 1])
a2[i] = a2[i + 1];
else
{
a2[i] = temp1;
break;
}
}
sum1 = sum1 - temp1 + temp2;
sum2 = sum2 - temp2 + temp1;
if (sum2 > sum1)
balance(sum2, sum1, a2, a1, n);
else
balance(sum1, sum2, a1, a2, n);
}
else
{
printf("\n\n SUM = %d\t",sum1);
display(a1, n);
printf("\n\n SUM = %d\t",sum2);
display(a2, n);
}
}
void divided_array(int a[], int n)
{
int a1[n/2], a2[n/2];
int sum1 = 0;
int sum2 = 0;
int k = 0;
int i;
sort_array(a,n);
a1[0] = a[n-1];
a2[0] = a[n-2];
for (i = n-2; i >= 2; i-=2)
{
sum1 += a1[k];
sum2 += a2[k];
k += 1;
if (sum1 > sum2)
{
a1[k] = a[i - 2];
a2[k] = a[i - 1];
}
else
{
a1[k] = a[i - 1];
a2[k] = a[i - 2];
}
}
sum1 += a1[k];
sum2 += a2[k];
if (sum2 > sum1)
balance(sum2, sum1, a2, a1, k+1);
else
balance(sum1, sum2, a1, a2, k+1);
}
I did not implement the function sort_array.
Better to use heap sort.
95 135 68 11 84 26 66 139 118 116 65 18
SUM = 469 135 118 95 84 26 11
SUM = 472 139 116 68 66 65 18
=========================================================
95 145 77 34 169 79 35 67 149 33 166 77
SUM = 561 169 149 95 79 35 34
SUM = 565 166 145 77 77 67 33
=========================================================
95 21 80 131 6 58 18 139 159 89 81 11
SUM = 441 139 131 81 58 21 11
SUM = 447 159 95 89 80 18 6
=========================================================
67 21 80 131 82 58 18 58 159 89 81 11
SUM = 427 159 89 82 58 21 18
SUM = 428 131 81 80 67 58 11