Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
// under the BSD license. The original license terms are given below:

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    /**
     * Returns the indices that would sort an array.
     * @param array Array.
     * @param ascending Ascending order.
     * @return Array of indices.
     */
    public static int[] Argsort(final double[] array, final boolean ascending) {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < indexes.length; i++) {
            indexes[i] = i;
        }
        Arrays.sort(indexes, new Comparator<Integer>() {
            @Override
            public int compare(final Integer i1, final Integer i2) {
                return (ascending ? 1 : -1) * Double.compare(array[i1], array[i2]);
            }
        });
        return asArray(indexes);
    }

    /**
     * Returns the indices that would sort an array.
     * @param array Array.
     * @param ascending Ascending order.
     * @return Array of indices.
     */
    public static int[] Argsort(final int[] array, final boolean ascending) {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < indexes.length; i++) {
            indexes[i] = i;
        }
        Arrays.sort(indexes, new Comparator<Integer>() {
            @Override
            public int compare(final Integer i1, final Integer i2) {
                return (ascending ? 1 : -1) * Integer.compare(array[i1], array[i2]);
            }
        });
        return asArray(indexes);
    }

    /**
     * Returns the indices that would sort an array.
     * @param array Array.
     * @param ascending Ascending order.
     * @return Array of indices.
     */
    public static int[] Argsort(final float[] array, final boolean ascending) {
        Integer[] indexes = new Integer[array.length];
        for (int i = 0; i < indexes.length; i++) {
            indexes[i] = i;
        }
        Arrays.sort(indexes, new Comparator<Integer>() {
            @Override
            public int compare(final Integer i1, final Integer i2) {
                return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);
            }
        });
        return asArray(indexes);
    }

    /**
     * Convert any number class to array of integer.
     * @param <T> Type.
     * @param array Array.
     * @return Integer array.
     */
    private static <T extends Number> int[] asArray(final T... array) {
        int[] b = new int[array.length];
        for (int i = 0; i < b.length; i++) {
            b[i] = array[i].intValue();
        }
        return b;
    }
}