Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array sort: Quick way to get a sorted list of indices of an array

The problem: Consider the following floats[]:

d[i] =     1.7 -0.3  2.1  0.5 

What I want is an array of int[] that represents the order of the original array with indices.

s[i] =       1    3    0    2 d[s[i]] = -0.3  0.5  1.7  2.1 

Of course it could be done with a custom comparator, a sorted set of custom objects, or by simply sorting the array and then searching for the indices in the original array (shudder).

What I am in fact looking for is the equivalent for the second return argument of Matlab's sort function.

Is there an easy way to do that (<5 LOC)? May there be a solution that does not need to allocate a new object for each element?


Update:

Thanks for your responses. Unfortunately, none of what has been proposed so far resembles the simple and efficient solution I was hoping for. I therefore openened a thread in the JDK feedback forum, proposing the addition of a new class-library function to address the issue. Lets see what Sun/Oracle thinks about the issue.

http://forums.java.net/jive/thread.jspa?threadID=62657&tstart=0

like image 219
edgar.holleis Avatar asked Jun 04 '09 17:06

edgar.holleis


People also ask

How do you sort an array by indices?

sort(long[], int, int) method sorts the specified range of the specified array of longs into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

What is the best way to sort an array in Java?

Using the sort() Method In Java, Arrays is the class defined in the java. util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)).


1 Answers

Simple solution to create an indexer array: sort the indexer comparing the data values:

final Integer[] idx = { 0, 1, 2, 3 }; final float[] data = { 1.7f, -0.3f,  2.1f,  0.5f };  Arrays.sort(idx, new Comparator<Integer>() {     @Override public int compare(final Integer o1, final Integer o2) {         return Float.compare(data[o1], data[o2]);     } }); 
like image 61
carloscs Avatar answered Sep 21 '22 07:09

carloscs