Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 257
Klausos Klausos Avatar asked Apr 03 '13 14:04

Klausos Klausos


People also ask

What is the starting index of ArrayList?

The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value.

How are the elements of ArrayList sorted?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.

What is the initial size of ArrayList?

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.


2 Answers

If the values are unique, you can use a Map<Double, Integer> to hold the value and initial order. You just need to sort the map keys and get the correspond value of each key.

like image 23
BobTheBuilder Avatar answered Oct 11 '22 02:10

BobTheBuilder


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)));
}
like image 113
Justin Avatar answered Oct 11 '22 02:10

Justin