0% found this document useful (0 votes)
10 views

Array Partition

This Java program takes in an array of integers as input, sorts the array using selection sort, and calculates the maximum sum of pairs by adding the minimum element from each pair in the sorted array. It runs the program repeatedly until the user presses 0.

Uploaded by

Fake XZVO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Array Partition

This Java program takes in an array of integers as input, sorts the array using selection sort, and calculates the maximum sum of pairs by adding the minimum element from each pair in the sorted array. It runs the program repeatedly until the user presses 0.

Uploaded by

Fake XZVO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

//Program to print the sum of the minimum of the pairs

import java.util.*;

public class ArrayPartition {

public static void main(String[] args){

Scanner s = new Scanner(System.in);

do{
run();
System.out.print("\nTo continue press 0: ");
} while(s.nextLine().charAt(0) == '0');

public static void run(){

Scanner sc = new Scanner(System.in);


System.out.print("Array size = ");

int[] arr = new int[sc.nextInt()];

if(arr.length%2!=0){
System.out.println("Invalid Input!");
return;
}

System.out.println("Enter elements: ");

for (int i = 0; i < arr.length; i++)


arr[i] = sc.nextInt();

selectionSort(arr);

System.out.println("Sorted Array: " +


. Arrays.toString(arr));

System.out.println("Max sum of pairs = " +


. calculateMaxSum(arr));

}
public static void selectionSort(int[] arr){

for(int i=0; i<arr.length-1; i++){

int minIndex = i;

for(int j=i+1; j<arr.length; j++){


if(arr[j]<arr[minIndex])
minIndex = j;
}

int temp = arr[i];


arr[i] = arr[minIndex];
arr[minIndex] = temp;
}

public static int calculateMaxSum(int[] arr){

int ans = 0;

for(int i=1; i<arr.length; i+=2)


ans+=arr[i];

return ans;

OUTPUT
Array size = 8
Enter elements:
3 8 1 5 0 2 7 3
Sorted Array: [0, 1, 2, 3, 3, 5, 7, 8]
Max sum of pairs = 17

To continue press 0: 1

You might also like