Sort array and return the original indices of each item in the sorted list, such that array[returnValue[k]] is the kth item in the sorted list. - Java java.lang

Java examples for java.lang:Math Array Function

Description

Sort array and return the original indices of each item in the sorted list, such that array[returnValue[k]] is the kth item in the sorted list.

Demo Code

/*//from  w  w w .ja v  a2 s . c  om
 *  Java Information Dynamics Toolkit (JIDT)
 *  Copyright (C) 2012, Joseph T. Lizier
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Vector;

public class Main{
    /**
     * Sort array and return the original indices of each item in the
     * sorted list, such that array[returnValue[k]] is the kth item in the
     * sorted list.
     * Sorting is done from smallest to largest.
     * 
     * @param array array of doubles to sort
     * @return list of original indices, in the sorted order of the array
     */
    public static int[] sortIndices(double[] array) {
        // Need an instance of MatrixUtils to get to member classes:
        MatrixUtils mUtils = new MatrixUtils();

        // First create the array of DoubleWithIndexForSort objects:
        DoubleWithIndexForSort[] objectArray = new DoubleWithIndexForSort[array.length];
        for (int i = 0; i < array.length; i++) {
            objectArray[i] = mUtils.new DoubleWithIndexForSort(array[i], i);
        }
        // Sort the array with original indices in place:
        Arrays.sort(objectArray,
                mUtils.new DoubleWithIndexForSortComparator());
        // Pull out the original indices:
        int[] arrayOfOriginalIndices = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            arrayOfOriginalIndices[i] = objectArray[i].originalIndex;
        }
        return arrayOfOriginalIndices;
    }
}

Related Tutorials