//TestIntegerArraySorting.java

import java.util.Arrays;
import java.util.Scanner;

public class TestIntegerArraySorting
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        int[] intArray = { 32, 3, 145, 78, 44, 61, 27 };

        System.out.println("\nPrinting values in the order entered ... ");
        for (int i : intArray)
        {
            System.out.print(i + " ");
        }
        System.out.print("\nPress Enter to continue ... ");
        keyboard.nextLine();

        System.out.println
        (
            "\nSorted in the default way "
            + "(increasing order) ... "
        );
        Arrays.sort(intArray);
        for (int i : intArray)
        {
            System.out.print(i + " ");
        }
        System.out.print("\nPress Enter to continue ... ");
        keyboard.nextLine();

        System.out.println("\nSorted in increasing order by last digit ... ");
        Integer[] integerArray =
        {
            32, 3, 145, 78, 44, 61, 27
        };
        Arrays.sort
        (
            integerArray,
            (Integer a, Integer b) ->
            Integer.compare(new Integer(a % 10), new Integer(b % 10))
        );
        for (int i : integerArray)
        {
            System.out.print(i + " ");
        }
        System.out.print("\nPress Enter to continue ... ");
        keyboard.nextLine();

        System.out.println("\nSorted in decreasing order by digit sum ... ");
        Integer[] integerArray2 = { 32, 3, 145, 78, 44, 61, 27 };
        Arrays.sort(integerArray2, (Integer a, Integer b) ->
        {
            int a_sum = 0;
            while (a / 10 != 0)
            {
                a_sum += a % 10;
                a /= 10;
            }
            a_sum += a;
            int b_sum = 0;
            while (b / 10 != 0)
            {
                b_sum += b % 10;
                b /= 10;
            }
            b_sum += b;
            return b_sum - a_sum;
            //The above line can/should be replaced by the
            //following recommended "better" alternative:
            //return Integer.compare(b_sum, a_sum);
        });
        for (int i : integerArray2)
        {
            System.out.print(i + " ");
        }
        System.out.print("\nPress Enter to continue ... ");
        keyboard.nextLine();
    }
}
/*  Output:

    Printing values in the order entered ...
    32 3 145 78 44 61 27
    Press Enter to continue ...

    Sorted in the default way (increasing order) ...
    3 27 32 44 61 78 145
    Press Enter to continue ...

    Sorted in increasing order by last digit ...
    61 32 3 44 145 27 78
    Press Enter to continue ...

    Sorted in decreasing order by digit sum ...
    78 145 27 44 61 32 3
    Press Enter to continue ...
*/
