Search code examples
javasortingcollectionsarraylist

Initial indexes of sorted elements of ArrayList


The following code implements sorting of nfit in ascending order.

public static void main(String[] args) {
    ArrayList<Double> nfit = new ArrayList<Double>();

    nfit.add(2.0);
    nfit.add(5.0);
    nfit.add(1.0);
    nfit.add(8.0);
    nfit.add(3.0);

    // Sort individuals in ascending order
    Collections.sort(nfit);

    System.out.print(nfit);

}

The output is:

[1.0, 2.0, 3.0, 5.0, 8.0]

My question is how to get initial indexes of sorted elements? In this example the answer to my question would be the following:

[2, 0, 4, 1, 3]

How can I get these indexes?


Solution

  • Copy the ArrayList and sort, then use indexOf.

    ArrayList<Double> nfit = new ArrayList<Double>();
    nfit.add(2.0);
    nfit.add(5.0);
    nfit.add(1.0);
    nfit.add(8.0);
    nfit.add(3.0);
    ArrayList<Double> nstore = new ArrayList<Double>(nfit); // may need to be new ArrayList(nfit)
    Collections.sort(nfit);
    int[] indexes = new int[nfit.size()];
    for (int n = 0; n < nfit.size(); n++){
        indexes[n] = nstore.indexOf(nfit.get(n));
    }
    System.out.println(Arrays.toString(indexes));
    

    If you wanted the indexes in an ArrayList,

    Collections.sort(nstore);
    for (int n = 0; n < nfit.size(); n++){
        nstore.add(n, nfit.indexOf(nstore.remove(n)));
    }
    Collections.sort(nfit);
    

    That will result in one sorted ArrayList nfit, and one ArrayList of indexes nstore.

    Edited: In the for loop

    for (int n = 0; n < nfit.size(); nfit++){
        nstore.add(n, nfit.indexOf(nstore.remove(n)));
    }
    

    The loop count must be iterated over n and not on nfit Find the corrected code:

    for (int n = 0; n < nfit.size(); n++){
        nstore.add(n, nfit.indexOf(nstore.remove(n)));
    }