Martin
Martin

Reputation: 31

sorting pairs of numbers in the list

I want to write a program which from a list of numbers selects pairs of numbers. But this pairs should by the sum of the smallest and the sum of the largest numbers . In the next step I want to sort them from the smallest to the largest to show sum of the smallest and sum of the largest numbers . Example 1 entrance: [1, 2, 4, 8, 9] output: The smallest pair [1, 2 = 3 ], the largest pair [8, 9 = 17]

How can I sort pairs of numbers ?

public class Tabli {
public static void main(String[] args) {

    int[] numbers = {12, 36, 2, 5,12,31};

    int sum0 = numbers[0] + numbers[1];
    System.out.println(sum0);

    int sum1 =numbers[1] +numbers[2];
    System.out.println(sum1);

    int sum2 =numbers[2] +numbers[3];
    System.out.println(sum2);

    int sum3 =numbers[3] +numbers[4];
    System.out.println(sum3);

    int sum4 =numbers[4] +numbers[5];
    System.out.println("End:"+sum4);

    int sum = 0;
    for (int i = 0; i< numbers.length; i++) {

            sum += numbers[i];

        }
    for (int j = 0; j < (numbers.length)-8; j++) {
        sum1 += numbers[j];
        System.out.println("Sum: " + sum);

    }
    System.out.println("Sum: " + sum1);
}
}

Upvotes: 0

Views: 194

Answers (2)

snowman
snowman

Reputation: 566

First sort the array

Arrays.sort(numbers);

therefore the max pair are the last 2 numbers

int max = numbers[numbers.length-1] + numbers[numbers.length-2];

and the min pair are the first 2 numbers

int min = numbers[0] + numbers[1];

Upvotes: 0

Andronicus
Andronicus

Reputation: 26036

Try this:

int[] numbers = {12, 36, 2, 5,12,31};
int min = numbers[0] + numbers[1]; // instantiate randomly
int max = numbers[0] + numbers[1]; // instantiate randomly
for (int i = 0; i < numbers.length - 1; i++) {
    min = Math.min(numbers[i] + numbers[i + 1], min);
    max = Math.max(numbers[i] + numbers[i + 1], max);
}
System.out.println(min + ", " + max);

The output is then:

7, 48

This solution is valid for any length of numbers array.

Edit

When numbers needs to be sorted, simply add Arrays.sort(numbers); right after numbers definition.

Upvotes: 1

Related Questions