Problem 4
/Problem 4
Complexity: Medium
You have been given a set of n integers. You need to write a program that will divide the set in two subsets of n/2 sizes each such that the difference of the sum of two subsets is as minimum as possible.
Note: n is even, hence sizes of two subsets must be strictly n/2/
// Imports
import java.util.Arrays;
import java.util.Scanner;
// Main class
public class PartitionSet
{
//Method to get sub arrays
public static void printSub(int[] arr)
{
int[] arr1 = new int[arr.length / 2];
int[] arr2 = new int[arr.length / 2];
Arrays.sort(arr);
for (int n = 1, index = 0, i = arr.length - 1; i > 0; i -= 2, n++)
{
if (n % 2 != 0)
{
arr1[index] = arr[i];
arr2[index++] = arr[i - 1];
} //End of if-block
else
{
arr2[index] = arr[i];
arr1[index++] = arr[i - 1];
}//End of else-block
}//End of for loop
System.out.println("Respective partitioned arrays are: \n" + Arrays.toString(arr1) +"\n And \n" + Arrays.toString(arr2));
}//End of method
// Main method
public static void main (String[] args)
{
// object of the Scanner class
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of the array : ");
// Reading size of array from user
int arr_length = sc.nextInt();
//Since it is given that array size should be even
if (arr_length % 2==0)
{
// Create array of given size
int[] arr = new int[arr_length];
// Object of the Scanner class
Scanner sc1 = new Scanner(System.in);
// Reading array elements from user
for (int i = 0; i < arr.length; i++)
{
System.out.println("Enter array element " + i + " : ");
arr[i] = sc1.nextInt();
}// End of for-loop
System.out.println("Original array is : \n " + Arrays.toString(arr));
//Calling method to get partitioned arrays
PartitionSet.printSub(arr);
}//End of if-block
else
{
System.out.println("Size of Array should be Even!!!");
}//End of else-block
/* Author @Ayesha Sumayya Khanum */
// End of main
}
// Class exit
}