Rank Numbers in Java
If you have a list of values in Java, you sometimes want to sort them. Other times, rather than sort them, you may want to determine the order that they would be sorted…or in other words rank them.
So if you create a list in this way:
ArrayList list = new ArrayList(); list.add(0); list.add(3); list.add(1);
…and sorted it, the list would be in the order 0, 1, 3 (smallest to largest).
If you ranked it, you would expect the result to be 0, 2, 1 (the first item is the smallest, the second item is the largest, etc.). You can perform the latter with the following method:
public static ArrayList Rank(ArrayList values) { ArrayList sortedValues = new ArrayList(values); Collections.sort(sortedValues); ArrayList ranks = new ArrayList(); for (int i=0; i<values.size(); i++) ranks.add(sortedValues.indexOf(values.get(i))); return ranks; }
This should work with an ArrayList that has any type of object that is set up to be sortable using the Comparable interface.
Note: This will perform slowly for very large lists. But I have tested it to confirm that the functionality works, so it should be a fine solution for relatively small arrays (with 10000 items or fewer). I welcome any suggestions on making it more efficient.